【问题标题】:What is the pythonic way to determine that two or more boolean evaluations are all False?确定两个或多个布尔评估都为假的pythonic方法是什么?
【发布时间】:2019-09-22 23:59:34
【问题描述】:

在像if (bool) and (bool): 这样的条件中,如果两个评估都是False,那么返回True 的最干净的表达式是什么?

我看到了许多从逻辑上使这项工作可行的选项,但在我看来,它们都显得凌乱。

【问题讨论】:

标签: python syntax boolean


【解决方案1】:

您可以使用all:

if all(not b for b in [bool_1, bool_2, ..., bool_n]):
# means: if all are not True (False)

any:

if not any([bool_1, bool_2, ..., bool_n]):
# means: if not any of them is True (same as above, logically)

或者,sum(仅限bool类型,否则使用sum(map(bool, [bool_1, ..., bool_n]))):

if sum([bool_1, bool_2, ..., bool_n]) == 0:   #  or, if not sum(...):
# True is 1, False is 0, if sum is 0, then all are 0 (False)

【讨论】:

  • 我还没有尝试过allany。谢谢你。这些看起来很有用。
  • 你不需要带有any的genexp。
  • 请注意,这些不一定是等效的。 not (a or b) 只会评估 baFalse,而 not any(a, b) 将始终评估 ab
  • @tobias_k 你是对的,但我的意思是(并且说)逻辑上等效,它们是。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-07-01
  • 1970-01-01
  • 2021-05-25
  • 2021-12-28
相关资源
最近更新 更多