如何按索引从列表中删除元素?

我找到了list.remove(),但这会缓慢地按值扫描列表中的项。


当前回答

您可以只搜索要删除的项目。这真的很简单。例子:

    letters = ["a", "b", "c", "d", "e"]
    letters.remove(letters[1])
    print(*letters) # Used with a * to make it unpack you don't have to (Python 3.x or newer)

输出:a c d e

其他回答

这听起来不像你在处理一个列表,所以我会保持简短。您希望使用pop,因为它将删除元素而不是列表元素,因此应该使用del。要调用python中的最后一个元素,它是“-1”

>>> test = ['item1', 'item2']
>>> test.pop(-1)
'item2'
>>> test
['item1']

pop对于从列表中删除和保留项目也很有用。del实际上在哪里丢弃了物品。

>>> x = [1, 2, 3, 4]

>>> p = x.pop(1)
>>> p
    2

使用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]

这是教程中的部分。

你可能想要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']

您可以只搜索要删除的项目。这真的很简单。例子:

    letters = ["a", "b", "c", "d", "e"]
    letters.remove(letters[1])
    print(*letters) # Used with a * to make it unpack you don't have to (Python 3.x or newer)

输出:a c d e