Python列表操作
Python列表操作
目录
创建列表
list1 = ['physics', 'chemistry', 1997, 2000]
list2 = [] #空列表
访问列表元素
list1 = ['physics', 'chemistry', 1997, 2000]
print(list1[0])
print(list1[0][0])
print(list1[0:2])
print(list1[-1])
#print(list1[-1][0]) 会报错,因为2000不是一个字符串,无法索引
输出如下:
physics
p
['physics', 'chemistry']
2000
更新列表元素
直接赋值更改:
list1 = ['physics', 'chemistry', 1997, 2000]
list1[0] = 'math'
print(list1)
输出:
['math', 'chemistry', 1997, 2000]
拼接列表
list1 = ['physics', 'chemistry', 1997, 2000]
list1.append(2020)
print(list1)
list2 = ['hahaha', 2021]
list3 = list1 + list2
print(list3)
输出:
['physics', 'chemistry', 1997, 2000, 2020]
['physics', 'chemistry', 1997, 2000, 2020, 'hahaha', 2021]
删除列表元素
使用del语句:
list1 = ['math', 'chemistry', 1997, 2000, 2020]
del list1[-1]
print(list1)
输出:
['math', 'chemistry', 1997, 2000]
使用pop()方法:
pop() 方法用于移除列表中的一个元素(默认最后一个元素),并且返回该元素的值。
list1 = ['math', 'chemistry', 1997, 2000]
p1 = list1.pop()
print(p1)
print(list1)
输出:
2000
['math', 'chemistry', 1997]
pop()方法也可以根据索引指定移除某一元素。
p2 = list1.pop(1)
print(p2)
print(list1)
输出:
'chemistry'
['math', 1997]
使用remove()方法:
remove()方法是根据特定值来删除元素。
list3 = [1,2,3,'a','b', 2]
list3.remove(1)
print(list3)
list3.remove('a')
print(list3)
输出:
[2, 3, 'a', 'b', 2]
[2, 3, 'b', 2]
若有重复值,remove()默认删除第一个指定的值。
list3.remove(2)
print(list3)
输出:
[3, 'b', 2]
可以通过一个while循环来删除列表里所有指定的值。
list4 = [1,2,3,'a','b', 2, 4, 2]
while 2 in list4:
list4.remove(2)
print(list4)
输出:
[1, 3, 'a', 'b', 4]
统计元素:count()方法
count() 方法用于统计某个元素在列表中出现的次数。
list1 = [1,2,3,'a','b', 2, 4, 2]
list1.count(2)
输出:
3
查找元素
in与not in:
判断某个元素是否在列表中,返回布尔值。
list1 = [1, 2, 3, 'a', 'b', 'c', 'a']
print(1 in list1)
print('a' in list1)
print('d' in list1)
输出:
True
True
False
index()方法:
index()方法可以查找元素并返回该元素的位置,如果有重复元素,则返回第一个目标元素的位置。
list1 = [1, 2, 3, 'a', 'b', 'c', 'a']
print(list1.index(2))
print(list1.index('a'))
输出:
1
3
最大值与最小值
max()与min()方法。
list1 = [1, 2, 3]
print(max(list1))
print(min(list1))
输出:
3
1
对列表排序
sort()方法
list0 = [1, 5, 3, 2, 9]
list0.sort()
print(list0)
list0.sort(reverse = True)
print(list0)
输出:
[1, 2, 3, 5, 9]
[9, 5, 3, 2, 1]
对列表逆序操作
使用[::-1]:
list1 = [1, 2, 3]
print(list1[::-1]) #原列表不变
print(list1)
输出:
[3, 2, 1]
[1, 2, 3]
使用reverse()方法:
list1 = [1, 2, 3]
print(list1.reverse()) #原列表改变
print(list1)
输出:
[3, 2, 1]
[3, 2, 1]

浙公网安备 33010602011771号