我很好奇逻辑运算符如何在集合中工作。考虑到这一点:
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'}
Run Code Online (Sandbox Code Playgroud)
我希望联合和交集的输出对于每个都相同。他们怎么可能不是?谁能解释一下?
你不能在 python 中覆盖逻辑and和的功能or。所以当你打电话时:
>>> set([1, 2, 3]) or set([2, 3, 4])
{1, 2, 3}
Run Code Online (Sandbox Code Playgroud)
它将它视为逻辑或,它将评估左侧为布尔值 true 并立即停止评估并返回左侧。相似地:
>>> set([1, 2, 3]) and set([2, 3, 4])
{2, 3, 4}
Run Code Online (Sandbox Code Playgroud)
被视为逻辑and,它将左侧评估为布尔值True,然后将右侧评估为布尔值,True从而返回右侧。
逻辑上and与or按位无关&,|在任何语言中都没有关系,包括 python。
| 归档时间: |
|
| 查看次数: |
739 次 |
| 最近记录: |