自用】Python列表常用操作"/>
【自用】Python列表常用操作
列表的增加:
list.append(obj) & list.extend(seq)
a=[1,2]
b=[3,4]
a.append(b) #将b列表当成一个元素,加入a列表
print(a)
a.extend(b) #将b列表的每一个元素逐一加入a列表
print(a)
输出结果:
[1, 2, [3, 4]]
[1, 2, [3, 4], 3, 4]
list.insert(index, obj)
a=[1,2,3,4]
a.insert(2,6) #2是需要插入的索引位置,6是要插入列表中的对象
print(a)
输出结果:
[1, 2, 6, 3, 4]
列表的删除
del Data[i]
song=["whish you were here","on the run","if","echoes"]
del song[2] #指定位置删除元素
for songname in song:print(songname)
输出结果:
whish you were here
on the run
echoes
list.pop([index=-1])
index :可选参数,要移除列表元素的索引值,不能超过列表总长度
默认为 index=-1,删除最后一个列表值
song=["whish you were here","on the run","if","echoes"]
song.pop()
for songname in song:print(songname)
print(" ")
song.pop(1)
for songname in song:print(songname)
输出结果:
whish you were here
on the run
ifwhish you were here
if
list.remove(obj)
song=["whish you were here","on the run","if","echoes"]
song.remove("if") #直接删除指定内容
for songname in song:print(songname)
列表的查看
in & not in
list=["a","b","c","e","d","e"]
findletter=input("请输入要查询的字母:")
if findletter in list:print("找到了")
else:print("没找到")
输出结果:
请输入要查询的字母:b
找到了
list.index(x[, start[, end]])
list=["a","c","b","e","c","e","d","e"]
print("e的索引值为:",list.index("e",0,5))
#在索引值[0,5)范围内,找到指定元素对应的下标
输出结果:
e的索引值为: 3
list.count(obj)
list=["a","c","b","e","c","e","d","e"]
print("e出现的次数:",list.count("e"))
输出结果:
e出现的次数: 3
列表的排序和反转
list.reverse() & list.sort( key=None, reverse=False)
reverse = True 降序, reverse = False 升序(默认)
list=["a","c","b","e","c","e","d","e"]
list.reverse()
print("列表反转后:",list)
list.sort()
print("升序:",list)
list.sort(reverse=True)
print("降序:",list)
输出的结果:
列表反转后: ['e', 'd', 'e', 'c', 'e', 'b', 'c', 'a']
升序: ['a', 'b', 'c', 'c', 'd', 'e', 'e', 'e']
降序: ['e', 'e', 'e', 'd', 'c', 'c', 'b', 'a']
学习参考:
1.=9&vd_source=84c909a3c400f0b1afb074cb83e7b0c1
2..html
更多推荐
【自用】Python列表常用操作
发布评论