基本上,您希望将一个元素添加到新列表中(如果一个元素存在而另一个元素中不存在)。这是一个可以做到的紧凑循环。对于两个列表中的每个元素(将它们与相连list1+list2
),如果其中一个元素中不存在该元素,我们将添加该元素:
[a for a in list1+list2 if (a not in list1) or (a not in list2)]
您可以像现在一样,通过显式遍历元素轻松地将其转换为更非Python的代码,但是老实说,我看不到要点(不是很重要):
def xor(list1, list2):
outputlist = []
list3 = list1 + list2
for i in range(0, len(list3)):
if ((list3[i] not in list1) or (list3[i] not in list2)) and (list3[i] not in outputlist):
outputlist[len(outputlist):] = [list3[i]]
return outputlist