- 创建一个普通列表
member = ['a','b','c']
- 创建一个混合列表
member = [1,2,3,'a','b','c',['d','e','f']]
- 创建一个空列表
member = []
append(元素),只能添加一个元素
test = ['a','b','c']
test.append('d')
print(test)
['a', 'b', 'c', 'd']
extend([元素,元素,元素])原理,用一个列表扩充另一个列表,可添加多个元素
test = ['a','b','c'] test.extend(['d','e','f']) print(test) ['a', 'b', 'c', 'd', 'e', 'f']
insert(元素的位置,所添加的元素)
test = ['a', 'b', 'c', 'd', 'e', 'f'] test.insert(1,'z') print(test) ['a', 'z', 'b', 'c', 'd', 'e', 'f']从列表中获取元素
跟数组一样我们可以根据列表的索引值来获取列表中的元素,索引值是从零开始
test = ['a', 'b', 'c', 'd', 'e', 'f'] print(test[0]) a从列表中删除元素
- remove()删除具体元素。
test = ['a', 'b', 'c', 'd', 'e', 'f'] test.remove('a')#删除a元素 print(test) ['b', 'c', 'd', 'e', 'f'] - del 删除列表中的某个元素或者整个列表,del是一条语句是内置函数。
test = ['a', 'b', 'c', 'd', 'd', 'e', 'f'] del test[0] print(test) ['b', 'c', 'd', 'd', 'e', 'f'] del test#删除整个列表
- pop() 从列表中取出最后一个元素并返回该元素。pop(索引值)从列表中取出索引值位置元素并返回该元素
test = ['a', 'b', 'c', 'd', 'd', 'e', 'f'] test.pop()#返回值为'f' print(test) ['a', 'b', 'c', 'd', 'd', 'e'] test.pop(0)#返回值为'a' print(test) ['b', 'c', 'd', 'd', 'e']
test = ['a', 'b', 'c', 'd', 'd', 'e', 'f'] test1 = test[1:3] print(test1) ['b', 'c'] test2 = test[:3] print(test2) ['a', 'b', 'c'] test3 = test[:] print(test3) ['a', 'b', 'c', 'd', 'd', 'e', 'f']列表的常用操作符
- 比较操作符
L1 = [123] L2 = [345] L1 < L2 True A1 = [1,2,3] A2 = [2,2,2] A1 < A2 True A1 > A2#只要第零个元素小,直接返回falsev False
- 逻辑操作符
Z1 = [1,2,3] Z2 = [2,3,4] Z4 = [1,2,3] (Z1 < Z2) and (Z1==Z4) True
- 连接操作符
Q1 = [1,2,3] Q2 = [4,5,6] Q = Q1 + Q2 print(Q) [1, 2, 3, 4, 5, 6]
- 重复操作符
N1 = [1,2,3] N2 = N1*2 print(N2) [1, 2, 3, 1, 2, 3] N1 *= 3 print(N1) [1, 2, 3, 1, 2, 3, 1, 2, 3]
- 成员关系操作符
M = ['a', 'b','c',[1,2,3]] 'a' in M True 'd' not in M True 1 in M False [1,2,3] in M True
- count()参数在列表中出现的次数
test = ['a', 'b', 'c', 'd', 'd', 'e', 'f'] test.count('a') 1 - index()获取元素在列表中首次出现的位置
test = ['a', 'b', 'c', 'd', 'd', 'e', 'f'] test.index('a') 0 #test.index('a',3) 元素a在3位置开始出现的次数 ,因为第三位后边没有元素a所以会报错 #test.index('a',1,4) 元素a在1位置开始4位置结束出现的次数 - reverse()将列表中元素逆序
test = ['a', 'b', 'c', 'd', 'd', 'e', 'f'] test.reverse() print(test) ['f', 'e', 'd', 'd', 'c', 'b', 'a']
- sort()将列表中成员升序排序
test = [5,6,7,9,2,3] test.sort() print(test) [2, 3, 5, 6, 7, 9] test.sort(reverse=True) print(test) [9, 7, 6, 5, 3, 2]
- copy()复制列表
test = ['a', 'b', 'c', 'd', 'd', 'e', 'f'] test2 = test.copy() print(test2) ['a', 'b', 'c', 'd', 'd', 'e', 'f']



