Python中集合使用or/and为何与|/&运算结果不符?
Python中集合
or/and与|/&的行为差异解析 现有两个集合:
set_one = {10,5,7} set_two = {10,1,3,6, 5, 7}
使用集合运算符|或union()方法可以正确得到并集:
set_one | set_two # union of two sets {1, 3, 5, 6, 7, 10} set_one.union(set_two) # same as above {1, 3, 5, 6, 7, 10}
但使用or得到的结果并非预期并集:
set_one or set_two {10, 5, 7} # Shouldn't this be {1, 3, 5, 6, 7, 10}?
同样,集合运算符&或intersection()方法能正确得到交集:
set_one & set_two # intersection of two sets {5, 7, 10} set_one.intersection(set_two) # same as above {5, 7, 10} set.intersection(set_one, set_two) # same as above {5, 7, 10}
而使用and得到的结果也不是预期交集:
set_one and set_two {1, 3, 5, 6, 7, 10} # Shouldn't this be {5, 7, 10}
原因解析
|和&是集合专属运算符,设计目的就是实现集合的并集、交集操作,和对应的union()、intersection()方法功能完全一致。or和and是通用布尔逻辑运算符,它们的行为不是针对集合设计的,而是遵循Python的"真值判断"和"短路求值"规则:- 对于
a or b:如果a的真值为True(Python中非空集合的真值都是True),直接返回a;只有当a为假(比如空集合set())时,才会返回b。 - 对于
a and b:如果a的真值为True,则返回b;如果a为假,返回a。
- 对于
在你的代码中,set_one和set_two都是非空集合,所以:
set_one or set_two直接返回第一个真值对象set_one,结果为{10,5,7}set_one and set_two返回第二个对象set_two,结果为{1,3,5,6,7,10}
内容的提问来源于stack exchange,提问作者Onyambu
相关产品推荐
相关产品推荐

