列表是Python中最常用的数据类型,以一个方括号出现,使用逗号做为分隔值。列表中的每个元素都分配一个数字,它的位置或索引都是从0开始,列表可以进行索引、添加、切片、加、乘或检查成员等。
-
访问列表中的元素;
a =[11,22,33,21]
print(a[0])
11
-
更新列表中的元素;
a =[11,22,33,21]
a[0]=1111
print(a)
[1111,22,33,21]
-
删除列表中的元素;
a =[11,22,33,21]
del a[0]
print(a)
[22,33,21]
-
列表操作符之长度;
a =[11,22,33,21]
print(len(a))
4
-
列表操作符之组合;
a =[11,22,33,21]
b =[99,33,44,66]
c = a + b
print(c)
[11,22,33,21,99,33,44,66]
-
列表操作符之重复;
a =[44]*4
print(a)
[44,44,44,44]
-
列表操作符之元素是否存在列表中;
a =[11,22,33,21]
print(3in a)
False
print(33in a)
True
-
列表操作符之迭代;
for i in[1,2,3,4,5]:
print(i)
1
2
3
4
5
-
列表操作之列表截取;
a =[11,22,33,21]
a[0]
11
a[-1]
21
a[-3]
22
a[1]
22
a[2]
33
a[1:]
[22,33,21]
-
len:列出元素的个数;
a =[11,22,33,21]
print(len(a))
4
-
max:列出列表中最大的元素;
a =[11,22,33,21]
print(max(a))
33
-
min:列出列表中小的元素;
a =[11,22,33,21]
print(min(a))
11
-
list:将元祖转换为列表;
a =(11,22,33,44)
b = list(a)
print(b)
[11,22,33,44]
print(type(b))
<class'list'>
-
append:在列表末尾添加新的元素;
a =[11,22,'cc',33,'aa',44,'dd']
a.append(55)
print(a)
[11,22,'cc',33,'aa',44,'dd',55]
-
extend:在列表末尾一次性追加另一个序列中的多个值(用新列表扩展原来的列表);
a =[11,22,'cc',33,'aa',44,'dd']
b =[66,'bb']
a.extend(b)
print(a)
[11,22,'cc',33,'aa',44,'dd',66,'bb']
-
clear:清空列表中所有的元素;
a =[11,22,'cc',33,'aa',44,'dd']
a.clear()
print(a)
[]
-
copy:复制列表,浅拷贝;
a =[11,22,'cc',33,'aa',44,'dd']
b = a.copy()
print(b)
[11,22,'cc',33,'aa',44,'dd']
-
count:统计某个元素在列表中出现的次数;
a =[11,22,'cc',33,'aa',44,'dd',44,33,44,'dd']
a.count(44)
3
-
index:在列表中找出某个元素第一个匹配项所在的位置;
a =[11,22,'cc',33,'aa',44,'dd',44,33,44,'dd']
a.index(33)
3
-
insert:在列表指定某个位置中插入元素;
a =[11,22,'cc',33,'aa',44,'dd',44,33,44,'dd']
a.insert(3,'qq')
a
[11,22,'cc','qq',33,'aa',44,'dd',44,33,44,'dd']
-
pop:在列表中指定删除一个元素,不指定默认删除末尾元素;
a =[11,22,'cc',33,'aa',44,'dd',44,33,44,'dd']
a.pop()
'dd'
print(a)
[11,22,'cc',33,'aa',44,'dd',44,33,44]
-
remove:移出列表中某个值第一个匹配的项,如果没有删除,就返回一个错误值;
a =[11,22,'cc',33,'aa',44,'dd',44,33,44,'dd']
a.remove('cc')
print(a)
[11,22,33,'aa',44,'dd',44,33,44,'dd']
-
reverse:反向列表中的元素;
a =[11,22,'cc',33,'aa',44,'dd',44,33,44,'dd']
a.reverse()
print(a)
['dd',44,33,44,'dd',44,'aa',33,'cc',22,11]
-
sort:排序列表中的元素;
a =[11,22,33,21]
a.sort()
print(a)
[11,21,22,33]
b =['ab','cc','zz','dd']
b.sort()
print(b)
['ab','cc','dd','zz']