Python 从列表中删除奇数

Python 从列表中删除奇数,python,Python,当我通过列表(4、5、5、4)时,以下代码失败。它返回(4,5,4)而不是(4,4)。这里怎么了?我无法理解为什么y列表中的更改会影响原始列表ls。请这样做 def purify(ls): y = ls for i in ls: if i % 2 != 0: y = y.remove(i) print y 在功能上 In [1]: a = (4, 5, 5, 4) In [2]: result = [i for i in a if

当我通过列表(4、5、5、4)时,以下代码失败。它返回(4,5,4)而不是(4,4)。这里怎么了?我无法理解为什么y列表中的更改会影响原始列表ls。

请这样做

def purify(ls):
    y = ls
    for i in ls:
        if i % 2 != 0:
          y = y.remove(i)

    print y
在功能上

In [1]: a = (4, 5, 5, 4)
In [2]: result = [i for i in a if not i % 2]
In [3]: result
Out[1]: [4, 4]
为了了解更多,我扩展了我的代码。从中你可以了解它是如何工作的

def purify(ls):
   return [i for i in ls if not i % 2]

一旦开始删除项目,索引就会更改。在循环中改变列表项时,对列表进行迭代不是一种好的做法。在列表的
ls[:]
切片上迭代:

def purify(input_list):
    result = []
    for i in input_list:
        if not i % 2:
            result.append(i)
    return result
或者只使用列表:

def purify(ls):
    for i in ls[:]:
        if i % 2 != 0:
            ls.remove(i)

以下代码更清晰、更容易理解:

[i for i in ls if i % 2 == 0]
[4,4]

l = [4, 5, 5, 4]

l = filter(lambda x: x % 2 == 0, l)

print(l)
正确版本:

remove(...)
    L.remove(value) -- remove first occurrence of value.
    Raises ValueError if the value is not present.
>>> filter(lambda x: x % 2 == 0, [4, 5, 5, 4])
[4, 4]
您的正确版本:

remove(...)
    L.remove(value) -- remove first occurrence of value.
    Raises ValueError if the value is not present.
>>> filter(lambda x: x % 2 == 0, [4, 5, 5, 4])
[4, 4]

但我正在编辑列表y,而不是原始列表ls。我无法理解为什么y列表上的remove函数会影响原始列表ls。这两个变量指向同一个对象。因此,如果您执行
x=y=['a']
,然后执行
x[0]=4
y
也会得到更新。