【发布时间】:2014-11-05 16:23:33
【问题描述】:
假设我有一个容器,例如字典或列表。测试容器的所有值是否等于给定值(例如None)的Python方法是什么?
我的幼稚实现是只使用一个布尔标志,就像我在 C 中被教导的那样,所以代码看起来像这样。
a_dict = {
"k1" : None,
"k2" : None,
"k3" : None
}
carry_on = True
for value in a_dict.values():
if value is not None:
carry_on = False
break
if carry_on:
# action when all of the items are the same value
pass
else:
# action when at least one of the items is not the same as others
pass
虽然这种方法工作得很好,但考虑到 Python 处理其他常见模式的出色表现,它感觉不太对劲。这样做的正确方法是什么?我想也许内置的 all() 函数会做我想要的,但它只测试布尔上下文中的值,我想与任意值进行比较。
【问题讨论】:
标签: python validation python-3.x containers