【自用】Python列表常用操作

编程入门 行业动态 更新时间:2024-10-06 04:02:32

【<a href=https://www.elefans.com/category/jswz/34/1765693.html style=自用】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列表常用操作

本文发布于:2024-02-19 14:54:08,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1764652.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:自用   常用   操作   列表   Python

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!