【问题标题】:Can somebody explain why this is happening [duplicate]有人可以解释为什么会这样[重复]
【发布时间】:2021-10-30 13:19:23
【问题描述】:

我们有:(set1,set2)

为什么print(set1 or set2) 返回set1 而不是(set1 | set2)print(set1 and set2) 返回set2 而不是set1.intersection(set2)

【问题讨论】:

  • @ThierryLathuille 我认为副本不太正确。 OP 询问为什么and& 以及or| 之间存在差异。他们不会问为什么orand 返回一个非布尔值
  • and 是布尔操作数,相当于您可能熟悉的其他语言中的&&& 是 Python 中的按位 and,它在集合中被连接到调用 set.intersection 方法(实际上,它是相反的方式,但想法是成立的)。 or|union 也是如此。
  • @DeepSpace 对,这个问题有两个部分,我添加了第二个关于&and 的副本。

标签: python python-3.x set operands


【解决方案1】:

这就是布尔操作数的工作原理

  • or

    • 如果左操作数是True/Truthy =>返回它
    • 如果左操作数是False/Falthy => 返回右操作数
  • and

    • 如果左操作数是False/Falthy =>返回它
    • 如果左操作数是True/Truthy => 返回右操作数

【讨论】:

  • 这不是 OP 所要求的。他们问为什么set1 and set2 不打电话给set1.intersection
【解决方案2】:

当你在 set1 和 set2 中有元素时,它们在布尔检查和 python 中变成True,当你像下面这样写时:

>>> True and 5
5

>>> True or 5
True

【讨论】:

  • 这不是问题要问的。
猜你喜欢
  • 2012-01-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-09
  • 2019-10-28
  • 2013-03-04
  • 2022-01-10
相关资源
最近更新 更多