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

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


当前回答

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

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

其他回答

已经提到了如何从列表中删除单个元素,以及不同的方法有哪些优点。但是,请注意,删除多个元素可能会出错:

>>> l = [0,1,2,3,4,5,6,7,8,9]
>>> indices=[3,7]
>>> for i in indices:
...     del l[i]
... 
>>> l
[0, 1, 2, 4, 5, 6, 7, 9]

原始列表的元素3和8(而不是3和7)已被删除(因为列表在循环过程中被缩短),这可能不是本意。如果您希望安全地删除多个索引,则应首先删除索引最高的元素,例如:

>>> l = [0,1,2,3,4,5,6,7,8,9]
>>> indices=[3,7]
>>> for i in sorted(indices, reverse=True):
...     del l[i]
... 
>>> l
[0, 1, 2, 4, 5, 6, 8, 9]

如前所述,最佳实践是del();或pop(),如果需要知道值。

另一种解决方案是仅重新堆叠所需的元素:

    a = ['a', 'b', 'c', 'd'] 

    def remove_element(list_,index_):
        clipboard = []
        for i in range(len(list_)):
            if i is not index_:
                clipboard.append(list_[i])
        return clipboard

    print(remove_element(a,2))

    >> ['a', 'b', 'd']

eta:hmm……不会处理负指数值,会思考并更新

我想是吧

if index_<0:index_=len(list_)+index_

会修补它…但突然间这个想法似乎很脆弱。有趣的思想实验。似乎应该有一种“正确”的方法来实现append()/list理解。

思考

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

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

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

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

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