【问题标题】:removing elements in list(Python)删除列表中的元素(Python)
【发布时间】:2019-07-21 07:19:46
【问题描述】:

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


【解决方案1】:

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

【讨论】:

  • 快速评论以确保完整性。 list.pop(index) 从列表中删除元素但也返回它。使用 del list[index] 只会删除它。
【解决方案2】:

您可以使用列表推导生成一个新列表,其中仅包含您想要保留的元素。

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?重复

【讨论】:

  • [x for x in oldList if x % 2] 可能比实现isEven 方法更容易。但不可重复使用。
  • 你是对的。我只是展示了一个完整的例子,其中列表理解中的条件可能比这个更复杂:)
  • 是的,是的。不批评;)
【解决方案3】:

试试这个:

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)

【讨论】:

    【解决方案4】:

    如果您想保留列表而不是创建新列表 (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.

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-02-11
      • 1970-01-01
      • 2016-07-13
      • 1970-01-01
      相关资源
      最近更新 更多