【问题标题】:What is the most 'pythonic' way to logically combine a list of booleans?逻辑组合布尔值列表的最“pythonic”方式是什么?
【发布时间】:2011-04-10 01:20:27
【问题描述】:

我有一个布尔值列表,我想使用和/或进行逻辑组合。扩展的操作将是:

vals = [True, False, True, True, True, False]

# And-ing them together
result = True
for item in vals:
    result = result and item

# Or-ing them together
result = False
for item in vals:
    result = result or item

上面的每一个都有漂亮的单行吗?

【问题讨论】:

标签: python list boolean


【解决方案1】:

all(iterable)

如果所有元素都返回True iterable 为真(或者如果 iterable 是空的)。

还有any(iterable)

如果有任何元素,则返回 True 可迭代 是真的。如果 iterable 为空,则返回 False

【讨论】:

    【解决方案2】:

    最好的方法是使用any()all() 函数。

    vals = [True, False, True, True, True]
    if any(vals):
       print "any() reckons there's something true in the list."
    if all(vals):
       print "all() reckons there's no non-True values in the list."
    if any(x % 4 for x in range(100)):
       print "One of the numbers between 0 and 99 is divisible by 4."
    

    【讨论】:

    • 我的布尔列表是由另一个列表上的列表理解生成的。现在我可以把它们都包起来了。不错!
    • 好吧,如果是这样的话,你可以把它做成一个生成器表达式:
    猜你喜欢
    • 2016-02-29
    • 2018-02-09
    • 1970-01-01
    • 1970-01-01
    • 2019-02-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多