我希望函数的结果是:
- 所有值的计算结果均为 False(无、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
[奖金]
这个函数应该怎么命名?
最佳答案
def unanimous(it):
it1, it2 = itertools.tee(it)
return all(it1) or not any(it2)
关于Pythonic 方法检查是否为 : all elements evaluate to False -OR- all elements evaluate to True,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4310744/