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

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


当前回答

使用以下代码从列表中删除元素:

list = [1, 2, 3, 4]
list.remove(1)
print(list)

output = [2, 3, 4]

如果要从列表中删除索引元素数据,请使用:

list = [1, 2, 3, 4]
list.remove(list[2])
print(list)
output : [1, 2, 4]

其他回答

另一种通过索引从列表中删除元素的方法。

a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

# remove the element at index 3
a[3:4] = []
# a is now [0, 1, 2, 4, 5, 6, 7, 8, 9]

# remove the elements from index 3 to index 6
a[3:7] = []
# a is now [0, 1, 2, 7, 8, 9]

a[x:y]指向从索引x到y-1的元素。当我们将列表的该部分声明为空列表([])时,这些元素将被删除。

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

    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

如果要删除列表中特定位置的元素,如第2、第3和第7个元素,则不能使用

del my_list[2]
del my_list[3]
del my_list[7]

因为在删除第二个元素之后,您删除的第三个元素实际上是原始列表中的第四个元素。您可以过滤原始列表中的第2、第3和第7个元素,并获得一个新列表,如下所示:

new_list = [j for i, j in enumerate(my_list) if i not in [2, 3, 7]]

使用以下代码从列表中删除元素:

list = [1, 2, 3, 4]
list.remove(1)
print(list)

output = [2, 3, 4]

如果要从列表中删除索引元素数据,请使用:

list = [1, 2, 3, 4]
list.remove(list[2])
print(list)
output : [1, 2, 4]

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

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