1、下标取值
li = ['a','b','c','d','e']
print(li[2])
#c
2、切片
li = ['a','b','c','d','e']
print(li[1:3])
#bc
3、列表的增删查改方法
(1)、增:
li = ['a','b','c','d','e']
li.append('111')
#li = ['a','b','c','d','e','111']
- insert()方法:通过指定位置插入数据,第一个参数是插入下标的位置,第二个是插入的值
li = ['a','b','c','d','e']
li.insert(0,666)
#li = [666,'a','b','c','d','e']
li = ['a','b','c','d','e']
li.extend('aa','bb',999)
li = ['a','b','c','d','e','aa','bb',999]
(2)、删除:
li = [11,22,33,44,55,'aa','11']
li.remove('aa')
#li = [11,22,33,44,55,'11']
- pop()方法:默认删除最后一个元素(可以指定下标进行删除)
li = [11,22,33,44,55,'aa','11']
li.pop() # li = [11,22,33,44,55,'aa']
li.pop(1) #li = [11,33,44,55,'aa']
li = [11,22,33,44,55,'aa','11']
li.clear() # li = []
li = [11,22,33,44,55,'aa','11']
del li[5] # li = [11,22,33,44,55,'11']
del li[0],[1] # li = [33,44,55,'11']
(3)、查询:
- 下标取值
- index()方法:找到第一个匹配的元素返回结果(下标值),没找到报错
li = [11,22,33,44,55,'aa','11']
res = li.index(33)
print(res) # 2
li = [11,22,33,44,55,'aa','11']
res = li.count(11)
print(res) # 1
(4)、改
li = [11,22,33,44,55,'aa','11']
li[5] = 66
print(li) # li = [11,22,33,44,55,66,'11']
(5)、其他方法
- sort()方法:排序(默认升序,加参数reverse = Ture 按降序排序)
li = [0, 1, 2, 3, 66, 5, 11, 22, 33]
li.sort() # [0, 1, 2, 3, 5, 11, 22, 33, 66]
li.sort(reverse = Ture) # [66, 33, 22, 11, 5, 3, 2, 1, 0]
li = [0, 1, 2, 3, 66, 5, 11, 22, 33]
li.reverse()
#[33,22,11,5,66,3,2,1,0]
li6 = [11,22,33,44,55,'aa','11']
li7=li6 #内存地址一样,一个改变另一个也改变
li8 = li6.coyp() # 内存地址不一样,两个独立