Python 支持集合 (有关集合的更多信息 https://docs.python.org/3/tutorial/datastructures.html#sets)。对于三个列表,它将是:
A = [1, 2, 3, 4]
B = [2, 3, 5, 6]
C = [3, 4, 5, 7]
As = set(A)
Bs = set(B)
Cs = set(C)
print((As ^ Bs ^ Cs) ^ (As & Bs & Cs))
对于列表列表(这是错误的 - 它所做的只是对所有集合进行异或,对所有集合进行与运算,然后对这两个结果进行异或 - 下面是正确的解决方案):
import functools
def do_xor(s1, s2):
return s1 ^ s2
def do_and(s1, s2):
return s1 & s2
def do_task(list_of_lists):
list_of_sets = list(map(set, list_of_lists))
xors = functools.reduce(do_xor, list_of_sets)
ands = functools.reduce(do_and, list_of_sets)
return xors ^ ands
A = [1, 2, 3, 4]
B = [2, 3, 5, 6]
C = [3, 4, 5, 7]
D=[A, B, C]
print(do_task(D))
正确的解决方案:
import functools
def do_or(s1, s2):
return s1 | s2
def do_task2(list_of_lists):
list_of_sets = list(map(set, list_of_lists))
list_of_intersects = [X & Y for X in list_of_sets for Y in list_of_sets if X is not Y]
intersects = functools.reduce(do_or, list_of_intersects)
ors = functools.reduce(do_or, list_of_sets)
return ors - intersects
lol33 = [
[1, 2],
[3, 2],
[3],
[3, 2, 4]
]
print(do_task2(lol33)) # {1, 4}