
如有翻译问题欢迎评论指出,谢谢。
Python如何按下标删除列表元素
-
Joan Venge asked:
- 怎么按下标移除Python列表中的元素。
- 我找到了
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']
-
How to remove an element from a list by index
-
Joan Venge asked:
- How do I remove an element from a list by index in Python?
怎么按下标移除Python列表中的元素。 - I found the
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
函数,但如果我想删除最后一个元素,该怎么写?它好像默认搜索列表,但我不希望它在执行的时候进行搜索。
- How do I remove an element from a list by index in Python?
-
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]
-
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']
-
近期评论