如何通过索引从列表中删除元素 [英] How to remove an element from a list by index
本文介绍了如何通过索引从列表中删除元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何在Python中按索引从列表中删除元素?
我找到了list.remove
方法,但是说我想删除最后一个元素,该怎么做?似乎默认的remove搜索列表,但是我不希望执行任何搜索.
解决方案
使用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]
此处是本教程中的部分. >
How do I remove an element from a list by index in 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.
解决方案
Use del
and specify the index of the element you want to delete:
>>> 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.
这篇关于如何通过索引从列表中删除元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文