我很好奇逻辑运算符是如何在集合中工作的。考虑一下这一点:
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'}
我希望联合和交集的输出都是相同的。他们怎么可能不是呢?有谁能解释一下吗?
发布于 2018-07-28 04:01:22
您不能覆盖python中逻辑and
和or
的功能。所以当你打电话的时候:
>>> set([1, 2, 3]) or set([2, 3, 4])
{1, 2, 3}
它将其视为逻辑或,它会将左侧求值为布尔值true,并立即停止求值并返回左侧。类似地:
>>> set([1, 2, 3]) and set([2, 3, 4])
{2, 3, 4}
被视为逻辑and
,它将对左侧求值为布尔True
,然后将右侧求值为布尔True
,从而返回右侧。
在任何语言中,逻辑and
和or
与逐位&
和|
都没有关系。
发布于 2018-07-28 04:06:17
我想最好用一个例子来说明。
or
返回计算为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'}
同时,and
需要计算所有表达式,只有当所有表达式的计算结果为真时,它才会返回最后一个表达式。
1 and 2 => 2
1 and 'a' and (1, 2, 3) => (1, 2, 3)
由于x
和y
都可以计算为True
x and y => y which is {'d', 'b', 'y', 'z', 'x'}
https://stackoverflow.com/questions/51564738
复制相似问题