查找出现在一个列表中但不在另一个列表中的元素反之亦然

问题描述

aList = [1,2]
bList = [2,3]    
aList = [i for i in aList if i not in bList ]
bList = [i for i in bList if i not in aList ]
print(aList)
print(bList)

我预计 aListbList 的结果是 [1][3],但结果是 [1][2,3]

我以为 i 中的 aList 会在 aList 生成后消失,我可以在 i 中使用 bList

i 中的 aList 如何影响 i 中的 bList

解决方法

这是因为当您执行 aList = [i for i in aList if i not in bList ] 时,您将 aList 的内容从 [1,2] 替换为 [1]

因此,bList 最终同时持有 [2,3],因为您的 aList 在执行 [1] 时只是 bList = [i for i in bList if i not in aList ]

为了使您的逻辑正常工作,您可以将 aListbList 存储在不同的变量中。例如:

aList = [1,2]
bList = [2,3]    
aListCopy = [i for i in aList if i not in bList ]
bListCopy = [i for i in bList if i not in aList ]
print(aListCopy)   # prints: [1]
print(bListCopy)   # prints: [3]

但是,对于您的用例,最好使用 set() 来查找存在于一个列表中但不在另一个列表中的元素。例如:

# Returns elements present in `aList` but not in `bList`
>>> set(aList) - set(bList)
set([1]) 

# Returns elements present in `bList` but not in `aList`
>>> set(bList) - set(aList)
set([3])

有关详细信息,请参阅 set() documentation

,

程序一步一步执行。声明:

aList = [i for i in aList if i not in bList ]

aList 的原始值从 [1,2] 替换为 [1]。然后,当控制到达这个语句时:

bList = [i for i in bList if i not in aList ]

状态是:

bList = [i for i in [2,3] if i not in [1] ]

它解释了你的输出。

bList = [2,3]

有一种方法可以解决这个问题,使用元组赋值

aList,bList =  [i for i in aList if i not in bList ],[i for i in bList if i not in aList ]

只有在评估了所有右侧表达式后,才会更新左侧的所有值。 现在你有: aList = [1] bList = [3]

此外,两个列表推导式中 i 的作用域仅在推导式 ([]) 内。

,

问题在于您正在重用变量 aList。在第 3 行使用不同的名称。

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...