You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.09 05:27:18