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

我找到了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

其他回答

使用del语句:

del listName[-N]

例如,如果要删除最后3项,则代码应为:

del listName[-3:]

例如,如果要删除最后8项,则代码应为:

del listName[-8:]

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

这是教程中的部分。

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

    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']

或者如果应删除多个索引:

print([v for i,v in enumerate(your_list) if i not in list_of_unwanted_indexes])

当然,也可以这样做:

print([v for i,v in enumerate(your_list) if i != unwanted_index])