python语法:列表的增删改查

append 尾部追加元素
lst = ['a', 'b', 'c']
lst.append('d')
print(lst) # ['a', 'b', 'c', 'd']
insert 任意位置插入元素
lst = ['a', 'b', 'c']
lst.insert(0, 'x')
lst.insert(len(lst), 'y')
print(lst) # ['x', 'a', 'b', 'c', 'y']
extend 将一个列表合并到另一个列表尾部
lst = ['a', 'b', 'c']
ext = ['d', 'e', 'f']
lst.extend(ext)
print(lst)

del 彻底删除元素

注意, del后不加列表下标时, 将清楚整个列表, 包括变量栈空间也会被移除

lst = ['a', 'b', 'c']
del lst[0]
print(lst) # ['b', 'c']
pop 弹出列表元素, 默认尾部弹出

pop 不加索引时, 默认弹出列表尾部元素, 加索引时, 弹出指定元素

lst = ['a', 'b', 'c', 'd']
lst.pop()
print(lst) # ['a', 'b', 'c']
lst.pop(1)
print(lst) # ['a', 'c']
remove 根据元素值移除元素

remove 每次只移除一个元素, 当有多个相同元素时, 移除相同元素中的第一个

lst = ['a', 'b', 'c', 'b', 'd']
lst.remove('b')
print(lst) # ['a', 'c', 'b', 'd']

通过下标修改
lst = ['a', 'b', 'c', 'b', 'd']
lst[3] = 'x'
print(lst) # ['a', 'b', 'c', 'x', 'd']

in, not in 元素是否存在于列表中
lst = ['a', 'b', 'c', 'b', 'd']
print('a' in lst) # True
print('a' not in lst) # False
index 元素是否存在与列表中, 不存在报异常
lst = ['a', 'b', 'c', 'b', 'd']
print(lst.index('b')) # 1
print(lst.index('x')) # ValueError: 'x' is not in list

count 元素在列表中的个数
lst = ['a', 'b', 'c', 'b', 'd']
print(lst.count('b')) # 2

排序

sort 列表排序
lst = ['a', 'b', 'c', 'b', 'd']
lst.sort(reverse = True)
print(lst) # ['d', 'c', 'b', 'b', 'a']
lst.sort()
print(lst) # ['a', 'b', 'b', 'c', 'd']
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

__万波__

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值