Pythonic 方法检查是否为 : all elements evaluate to False -OR- all elements evaluate to True

标签 python

我希望函数的结果是:

  • 所有值的计算结果均为 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/

相关文章:

python - 如何使用 all() 内置函数?

python - 禁用 Pygame 控制台输出

python - 在 Python/Seaborn 的图例中显示置信区间

python - 如何访问/修改函数闭包中的变量?

python - 清除整个根部

python - 如何使用 python 在 Raspberry Pi 上打开 PowerPoint?

python - Django:将模板值发布到 View

python - 如果指定了 file,则创建并打印到新文件,否则只是 std.out

python - 日期时间索引KeyError : 'the label [2000-01-03 00:00:00] is not in the [index]'

Python 脚本未创建足够的输出行