python集合中的逻辑运算符

python集合中的逻辑运算符,python,set,Python,Set,我很好奇逻辑运算符是如何在集合中工作的。联合声明如下: x = set('abcde') y = set('bdxyz') # union print(x | y) # output: {'d', 'b', 'y', 'e', 'z', 'x', 'c', 'a'} print(x or y) # output: {'d', 'b', 'e', 'c', 'a'} # intersection print(x and y) # output: {'d', 'b', 'y', 'z', 'x

我很好奇逻辑运算符是如何在集合中工作的。联合声明如下:

x = set('abcde')
y = set('bdxyz')

# union
print(x | y) # output: {'d', 'b', 'y', 'e', 'z', 'x', 'c', 'a'}
print(x or y) # output: {'d', 'b', 'e', 'c', 'a'} 

# intersection
print(x and y) # output: {'d', 'b', 'y', 'z', 'x'}
print(x & y) # output: {'b', 'd'}

我希望并集和交集的输出都是相同的。他们怎么可能不是呢?有人能解释一下吗?

在python中不能重写逻辑and和or的功能。所以当你打电话时:

>>> set([1, 2, 3]) or set([2, 3, 4])
{1, 2, 3}
它将其视为逻辑or,将左侧求值为布尔true,并立即停止求值并返回左侧。同样地:

>>> set([1, 2, 3]) and set([2, 3, 4])
{2, 3, 4}
被视为逻辑and,它将左侧求值为布尔真,然后将右侧求值为布尔真,从而返回右侧


逻辑and和or与任何语言(包括python)中的按位and没有关系。

我想最好用一个例子来说明

或返回计算结果为True的第一个值

# any non-zero integer is True
1 or 0 => 1
0 or 1 or 2 => 1
0 or 0 or 2 => 2
因为非空集合x的计算结果为True

x or y => x  which is {'d', 'b', 'e', 'c', 'a'} 
x and y => y  which is {'d', 'b', 'y', 'z', 'x'}
同时,需要计算所有表达式,并且只有当所有表达式的计算结果都为True时,才会返回最后一个表达式

1 and 2 => 2
1 and 'a' and (1, 2, 3) => (1, 2, 3)
因为x和y都可以计算为真

x or y => x  which is {'d', 'b', 'e', 'c', 'a'} 
x and y => y  which is {'d', 'b', 'y', 'z', 'x'}

因为按位运算符不同于布尔逻辑运算符,我不知道为什么您希望它们是相同的。此外,您的输出对于联合是不正确的。逻辑运算符应为first这与要设置的操作数无关。这就是所有类型的and和or的工作方式。尝试1或2和50或0。x或y与x | y不同。后者是集合的并集。前者说的是返回第一个Truthy值。@MatthewStory实际上,它并没有输入错误:@MatthewStory我同意。由于输出不一致,我被这篇文章吸引住了。如果Python真的那样工作,我会呕吐。真让人心烦。