删除列表中的元素(Python)

问题描述 投票:-2回答:4

我试过执行这个,但它不能正常工作。我的目标是删除除以2的所有数字。有人可以告知错误。我真的不明白为什么'4','8'仍在那里。

list = [2,4,9,0,4,6,8,3,43,44]
for e in list:
    if e%2==0:
        list.remove(e)
        print(list)
python python-3.x
4个回答
1
投票

如果要保留列表而不是创建新列表(the answer by Thomas Milox is a good one otherwise),则应按索引向后遍历列表。当您在列表中向前迭代时从列表中删除元素时,您可能跳过某些元素,而不是处理它们。向后移动可确保没有列表元素删除移动您可能仍希望处理的任何元素。

以下是这可能会查找代码的示例:

list = [2, 4, 9, 0, 4, 6, 8, 3, 43, 44]
for i in range(len(list) - 1, -1, -1):  # start at the last element, go until the first one (index 0 - the last value in the range method will not be reached), go backwards
    if list[i] % 2 == 0:
        del list[i]

You can read a bit more about removing an element by index instead of by value here.这是必需的,因为否则您将错误的位置上的列表变为重复值。它也可能更快一点,因为removene要遍历列表,搜索要删除的元素,而del list[i]可能会查找需要通过索引删除的元素。

Iterating backward through a list is also covered here.


3
投票

您可以使用列表推导来生成仅包含要保留的元素的新列表。

newList = [x for x in oldList if not isEven(x)]

功能isEven执行以下操作:

def isEven(target):
    return target % 2 == 0

顺便说一句,你的问题是以下How to remove items from a list while iterating?的副本


1
投票

您可以尝试将list.pop()与要删除的元素的位置一起使用。 '2'和'4'仍在那里,因为当你删除它们之前的数字时会跳过它们(当你删除'2'时,'4'被移动到前一个位置)


1
投票

试试这个:

l = [2, 3, 4, 5, 9, 10,30,45]
new=[el for el in l if el % 2]
print(new)

实际上,当您从列表中删除元素时,索引会发生更改。所以,你可以做这个列表理解。你也可以使用:

l = [2, 3, 4, 5, 9, 10,30,45]
new=[filter(lambda x: x % 2, l)]
print(new)
© www.soinside.com 2019 - 2024. All rights reserved.