品易云推流 关闭
文章详情页
文章 > Python常见问题 > python列表中去掉第几个值的方法

python列表中去掉第几个值的方法

头像

yang

2020-05-09 13:55:323592浏览 · 0收藏 · 0评论

python中关于删除list中的某个元素,一般有三种方法:remove、pop、del:

1、remove: 删除单个元素,删除首个符合条件的元素,按值删除

举例说明:

>>> str=[1,2,3,4,5,2,6]
>>> str.remove(2)
>>> str

输出结果:

[1, 3, 4, 5, 2, 6]

2、pop: 删除单个或多个元素,按位删除(根据索引删除)

>>> str=[0,1,2,3,4,5,6]
>>> str.pop(1) #pop删除时会返回被删除的元素
>>> str

输出结果:

[0, 2, 3, 4, 5, 6]

3、del:它是根据索引(元素所在位置)来删除

举例说明:

>>> str=[1,2,3,4,5,2,6]
>>> del str[1]
>>> str

输出结果:

[1, 3, 4, 5, 2, 6]

更多Python知识请关注Python视频教程栏目。

关注

关注公众号,随时随地在线学习

本教程部分素材来源于网络,版权问题联系站长!

底部广告图