删除列表中的元素(Python)

时间:2019-02-27 14:26:36

标签: python python-3.x

我尝试执行此操作,但无法正常工作。我的目标是删除所有数字除以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)

4 个答案:

答案 0 :(得分: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 :(得分:1)

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

答案 2 :(得分: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)

答案 3 :(得分: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. 这是必需的,因为否则您会在错误的位置上更改列表以获取重复值。由于remove需要遍历列表,因此在搜索要删除的元素的同时del list[i]可能会查找需要通过索引删除的元素,这可能会更快一些。

Iterating backward through a list is also covered here.