Pythonic方法检查是否:所有元素评估为False -OR-所有元素评估为True

Bel*_*dez 13 python

我希望函数的结果是:

  • 所有值都计算为False(None,0,空字符串) - > True
  • 所有值都评估为True - > True
  • 其他每一个案例 - >错误

这是我的尝试:

>>> def consistent(x):
...  x_filtered = filter(None, x)
...  return len(x_filtered) in (0, len(x))
...
>>> consistent((0,1))
False
>>> consistent((1,1))
True
>>> consistent((0,0))
True
Run Code Online (Sandbox Code Playgroud)

[奖金]

该功能应该命名为什么?

Ign*_*ams 24

def unanimous(it):
  it1, it2 = itertools.tee(it)
  return all(it1) or not any(it2)
Run Code Online (Sandbox Code Playgroud)

  • `itertools.tee`是一个触摸,使得这个答案值得放入工具包模块.您不必考虑发送的内容. (3认同)

dka*_*ins 11

def all_bools_equal(lst):
    return all(lst) or not any(lst)
Run Code Online (Sandbox Code Playgroud)

请参阅:http://docs.python.org/library/functions.html#all

请参阅:http://docs.python.org/library/functions.html#any

  • @Gerrat - 如果只有StackOverflow将Python解释器构建到答案框中;-) (4认同)