根据 Wolfram,上述阴影区域应该表示:
A XOR B XOR C XOR (A AND B AND C)
如何将此内容翻译成Python代码?该代码必须与上述表达式中提供的集合操作密切相关,至少这是首选。代码必须足够通用,以处理超过3个列表。 更新: 看起来Wolfram正在显示一个错误的文氏图?实际上,我们想要的是:
(A XOR B XOR C) - (A AND B AND C)
我无法在Wolfram中表示这个。
根据 Wolfram,上述阴影区域应该表示:
A XOR B XOR C XOR (A AND B AND C)
(A XOR B XOR C) - (A AND B AND C)
我无法在Wolfram中表示这个。
Python支持集合(更多关于集合的信息)。对于三个列表,它将是:
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}
&
[交集] 和 |
[并集] 来达到你的目的。此信息来源于@WPedrak。A = {1, 2, 3, 4}
B = {2, 3, 5, 6}
C = {3, 4, 5, 7}
lst = [A, B, C]
result = (A | B | C) - ((A & B) | (A & C) | (B & C) | (A & B & C))
# {1, 6, 7}
解释
我们取所有元素的并集,减去所有交集。参见@WPedrak的解决方案以获取通用情况。
lol33 = [ [1, 2], [3, 2], [3], [3, 2, 4] ]
那么do_task(lol3)
返回{1, 2, 3, 4}
。这是不正确的,对吗? - lifebalancedo_or
写成 lambda 函数:intersects = functools.reduce(lambda s1,s2: s1|s2, i)
- Vasilis