IF语句不适用于列表差异

Pra*_*eep 3 python django list

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

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")
Run Code Online (Sandbox Code Playgroud)

Wil*_*sem 7

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

如果要查找包含in中的元素以及list1in中list2的元素list2和not中的元素的列表,list1则应在此处使用对称的集差,这可以通过操作^来执行,例如:

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

list3 = list(set(list1) ^ set(list2))
Run Code Online (Sandbox Code Playgroud)

另一方面,如果要查找list2不在中的元素list1,则应交换操作数:

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

list3 = list(set(list2) - set(list1))
Run Code Online (Sandbox Code Playgroud)

如果使用,则-可以按照以下方法获得集合差异 [wiki](或补充):

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

对称集差 [wiki](或取并集)为:

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

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

if list3:  # not empty
  print(list3)
else: # is empty
  print("None")
Run Code Online (Sandbox Code Playgroud)