查找一个列表中存在但另一个列表中不存在的元素(反之亦然)

Find elements present in one list but not in another list (and vice versa)

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] .

我以为aList里的i做完aList就没了,我可以用bList里的i.

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

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

是因为你在执行aList = [i for i in aList if i not in bList ]的时候,把你的aList的内容从[1,2]替换成了[1].

因此,bList 最终持有两个 [2,3],因为你的 aList 在执行 bList = [i for i in bList if i not in aList ].

时只是 [1]

为了使您的逻辑工作,您可以将 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在两个列表推导中的范围仅在推导([])内。