首页 > 解决方案 > IF 语句不适用于列表差异

问题描述

尝试使用以下代码获取两个列表之间差异的结果,但似乎不起作用。

list1 = ['one', 'two', 'three']
list2 = ['one', 'two', 'three', 'four']


list3 = list(set(list1) - set(list2))

if not list3: #if not empty, print list3
  print(list3)
else: # if empty print none
  print("None")

标签: pythondjangolist

解决方案


在您的代码示例中,list3确实是空的,因为其中的所有元素list1也在其中list2

如果您正在寻找一个列表,其中包含 in list1that not in和 in和 not inlist2的元素,您应该在这里使用对称集差异,这可以使用operator执行,例如:list2list1^

list1 = ['one', 'two', 'three']
list2 = ['one', 'two', 'three', 'four']

list3 = list(set(list1) ^ set(list2))

另一方面,如果你正在寻找list2不在的元素list1,你应该交换操作数:

list1 = ['one', 'two', 'three']
list2 = ['one', 'two', 'three', 'four']

list3 = list(set(list2) - set(list1))

如果您使用-,您将获得设置差异[wiki](或补码),如下所示:

A ∖ B = { a∈ A | ∉ B }

对称集差异[wiki](或析取联合)是:

A ⊕ B = (A ∖ B) ∪ (B ∖ A)

注意:注意非空列表的真实性是,空列表的真实性TrueFalse。因此,您可能应该将打印逻辑重写为:

if list3:  # not empty
  print(list3)
else: # is empty
  print("None")

推荐阅读