列表(list)

  • 通过list创建对象,li = [1, 2, "age", "umbrella", [19, 10], "gxgd"]

中括号括起来

,分割每个元素

列表中的元素可以是数字、字符串、列表、布尔值(所有的值都能放进去)

“集合”内部可放置任何东西

可以通过索引取值,如:print(li[2])可获取列表内第二个元素,索引取值可以一直往里找





li = [1,12,9,"age",["雨伞",["19",10],"雨衣"],"umbrella","clothes"]
v = li[4][1][0][1]
print(v)


也支持切片取值,结果也是列表,如:print(li[3:-1])

支持for循环和while循环



li = [1, 2, "age", "umbrella", [19, 10], "gxgd"]
for item in li:
print(item)


列表元素可以被修改,索引、切片皆可用



li = [1, 2, "age", "umbrella", [19, 10], "gxgd"]
li[2] = [11, 22, 33]
li[1:3] = [120, 90]
print(li)


列表元素可以删除,如:del li[1]——索引:某个位置元素的修改,del li[1:3] ——切片:某段元素修改

支持用 in 判断某元素是否在列表内



li = [1, 2, "age", "umbrella", [19, 10], "gxgd"]
v = 120 in li
print(v)


 

  • 将字符串等转化为列表 list (内部执行for循环,所以数字不行)



v = "umbrella"
new_li = list(v)
print(new_li)


 

  • 列表元素合并成字符串

同时包含数字和字符串时——自己写for循环



li = [11,22,33,"125","umbrella"]
v = " "
for i in li:
v = v + str(i)
print(v)


 

 只有字符串时——join



li = ["125","umbrella"]
v = "".join(li)
print(v)


 

list类中的方法:

  • append() 在原来值后面追加新值,追加值可以是字符串、列表、数字



li = ["125","umbrella"]
v = li.append(5)
print(v)
print(li)


 

  • clear() 清空列表



li = ["125","umbrella"]
li.clear()
print(li)


 

  • copy() 浅拷贝



li = ["125","umbrella"]
v = li.copy()
print(v)


 

  • count() 计算元素出现个数



li = ["125","umbrella","125",125,75]
v1 = li.count("125")
v2 = li.count(125)
print(v1,v2)


 

  • extend() 扩展元列表,括号里的参数放可迭代对象(列表、字符串等可进行for循环的)。注意区分append,append将括号内容作为一个整体放到列表最后;extend做了一个for循环,将元素挨个依次放入



li = ["125","umbrella","125",125,75]
li.append([666,"雨伞"])
print(li)



li = ["125","umbrella","125",125,75]
li.extend([666,"雨伞"])
print(li)


 

  • index() 根据值获取当前索引位置,默认从左往右找



li = [125,"125","umbrella","125",125,75]
v = li.index(125)
print(v)


 

  • insert() 在指定索引位置插入元素



li = [125,"125","umbrella","125",125,75]
li.insert(0,"fighting")
print(li)


 

  • pop() 删除某个索引的值(未指定索引情况下默认删最后一个),可获得到删掉的值



li = [125,"125","umbrella","125",125,75]
v = li.pop(1)
print(li)
print(v)


 

  • remove() 删除列表中的某个指定值,默认左边优先(PS:删除方式总结——pop;remove;clear;del li[0] 索引删;del li[1:2] 切片删 )



li = [125,"125","umbrella","125",125,75]
li.remove(125)
print(li)


 

  • reverse() 将当前列表进行反转



li = [125,"125","umbrella","125",125,75]
li.reverse()
print(li)


 

  • sort() 对列表进行排序(可从大到小或从小到大)



li = [125,1,8,9,125,75]
li.sort()
print(li)