列表中存放的数据是可以进行修改的,比如"增"、"删"、"改""
>>> a=[123,345]
>>> a.append(678)
>>> a
[123, 345, 678]
2.extend可以将另一个集合中的元素逐一添加到列表中
a=['a','b','c']
b=['d','e','f']
>>> a.extend(b)
>>> a
['a', 'b', 'c', 'd', 'e', 'f']
3.insert
insert(index, object) 在指定位置index前插入元素object
>>> a=['a','b','c']
python中查找的常用方法为:
nameList = ['xiaoWang','xiaoZhang','xiaoHua']
findName = input('请输入要查找的姓名:')
if findName in nameList:
print('在字典中找到了相同的名字')
else:
print('没有找到')
>>> a = ['a', 'b', 'c', 'a', 'b']
>>> a.index('a', 1, 3) # 注意是左闭右开区间
Traceback (most recent call last):
File "" , line 1, in
ValueError: 'a' is not in list
>>> a.index('a', 1, 4)
3
>>> a.count('b')
2
>>> a.count('d')
0
列表元素的常用删除方法有:
demo:(del)
movieName = ['加勒比海盗','骇客帝国','第一滴血','指环王','霍比特人','速度与激情']
print('------删除之前------')
for tempName in movieName:
print(tempName)
del movieName[2]
print('------删除之后------')
for tempName in movieName:
print(tempName)
demo:(pop)
movieName = ['加勒比海盗','骇客帝国','第一滴血','指环王','霍比特人','速度与激情']
print('------删除之前------')
for tempName in movieName:
print(tempName)
movieName.pop()
print('------删除之后------')
for tempName in movieName:
print(tempName)
demo:(remove)
movieName = ['加勒比海盗','骇客帝国','第一滴血','指环王','霍比特人','速度与激情']
print('------删除之前------')
for tempName in movieName:
print(tempName)
movieName.remove('指环王')
print('------删除之后------')
for tempName in movieName:
print(tempName)
sort方法是将list按特定顺序重新排列,默认为由小到大,参数reverse=True可改为倒序,由大到小。
reverse方法是将list逆置。
>>> a = [1, 4, 2, 3]
>>> a
[1, 4, 2, 3]
>>> a.reverse()
>>> a
[3, 2, 4, 1]
>>> a.sort()
>>> a
[1, 2, 3, 4]
>>> a.sort(reverse=True)
>>> a
[4, 3, 2, 1]