IF语句不适用于列表差异

时间:2019-07-29 08:37:00

标签: 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")

2 个答案:

答案 0 :(得分:7)

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

如果您要查找包含list1中不在list2中的元素以及list2中但不在list1中的元素的列表,则您应该在此处使用对称集差异,这可以通过 ^运算符执行,例如:

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))

如果您使用-,则会获得set difference [wiki](或 complement ),如下所示:

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

symmetrical set difference [wiki](或析取联合)为:

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

  

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

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

答案 1 :(得分:2)

这是使用in

的另一种方法
list1 = ['one', 'two', 'three']
list2 = ['one', 'two', 'three', 'four']

list3 = []
for value in list2:
    if value not in list1:
        list3.append(value)

print(list3)

# outputs ['four']