代码之家  ›  专栏  ›  技术社区  ›  BobC

什么是最“pythonic”的方式来逻辑地组合布尔列表?

  •  30
  • BobC  · 技术社区  · 16 年前

    我有一个布尔的列表,我想用and/or逻辑地组合起来。扩大的业务将是:

    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
    

    3 回复  |  直到 16 年前
        1
  •  105
  •   NullUserException Mark Roddy    16 年前

    看到了吗 all(iterable) :

    True 如果 可迭代的 是真的(或者 可迭代的

    以及 any(iterable) :

    如果 可迭代的 这是真的。如果 可迭代的 False .

        2
  •  12
  •   Jerub    16 年前

    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."