Mic*_*ard 3 python validation containers python-3.x
假设我有一个容器,如字典或列表.如果容器的所有值都等于给定值(例如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
Run Code Online (Sandbox Code Playgroud)
虽然这种方法运行得很好,但考虑到Python如何处理其他常见模式,它感觉不对.这样做的正确方法是什么?我想也许内置all()
函数会做我想要的,但它只测试布尔上下文中的值,我想比较任意值.
all
如果添加生成器表达式,仍可以使用:
if all(x is None for x in a_dict.values()):
Run Code Online (Sandbox Code Playgroud)
或者,使用任意值:
if all(x == value for x in a_dict.values()):
Run Code Online (Sandbox Code Playgroud)