文章首发及后续更新:https://mwhls.top/3067.html
新的更新内容请到mwhls.top查看。
无图/无目录/格式错误/更多相关请到上方的文章首发页面查看。
目录 1. Python如何按下标删除列表元素 2. How to remove an element from a list by indexstackoverflow热门问题目录
如有翻译问题欢迎评论指出,谢谢。
Joan Venge asked:
list.remove
函数,但如果我想删除最后一个元素,该怎么写?它好像默认搜索列表,但我不希望它在执行的时候进行搜索。Answers:
unbeknown – vote: 2140
用del
可以删除指定下标的元素:
>>> a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> del a[-1]
>>> a
[0, 1, 2, 3, 4, 5, 6, 7, 8]
且支持分片删除:
>>> del a[2:4]
>>> a
[0, 1, 4, 5, 6, 7, 8, 9]
教程见此。
Jarret Hardie – vote: 763
试试pop
:
a = [‘a’, ‘b’, ‘c’, ‘d’]
a.pop(1)
# now a is [‘a’, ‘c’, ‘d’]
无参数的pop
默认删除最后一个元素:
a = [‘a’, ‘b’, ‘c’, ‘d’]
a.pop()
# now a is [‘a’, ‘b’, ‘c’]
Joan Venge asked:
list.remove
method, but say I want to remove the last element, how do I do this? It seems like the default remove searches the list, but I don\’t want any search to be performed.list.remove
函数,但如果我想删除最后一个元素,该怎么写?它好像默认搜索列表,但我不希望它在执行的时候进行搜索。Answers:
unbeknown – vote: 2140
Use del
and specify the index of the element you want to delete:
用del
可以删除指定下标的元素:
>>> a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> del a[-1]
>>> a
[0, 1, 2, 3, 4, 5, 6, 7, 8]
Also supports slices:
且支持分片删除:
>>> del a[2:4]
>>> a
[0, 1, 4, 5, 6, 7, 8, 9]
Here is the section from the tutorial.
教程见此。
Jarret Hardie – vote: 763
You probably want pop
:
试试pop
:
a = [‘a’, ‘b’, ‘c’, ‘d’]
a.pop(1)
# now a is [‘a’, ‘c’, ‘d’]
By default, pop
without any arguments removes the last item:
无参数的pop
默认删除最后一个元素:
a = [‘a’, ‘b’, ‘c’, ‘d’]
a.pop()
# now a is [‘a’, ‘b’, ‘c’]