Python 如何测试容器中所有项目的值?
假设我有一个容器,比如字典或列表。如果容器的所有值都等于给定值(例如Python 如何测试容器中所有项目的值?,python,validation,python-3.x,containers,Python,Validation,Python 3.x,Containers,假设我有一个容器,比如字典或列表。如果容器的所有值都等于给定值(例如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
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处理其他常见模式的能力,它感觉不太好。正确的方法是什么?我原以为内置函数可以实现我想要的功能,但它只在布尔上下文中测试值,我想与任意值进行比较。如果您添加一个: 或者,使用任意值:
if all(x == value for x in a_dict.values()):
与示例中的
carry_on
一致不是x不是None吗?我认为该示例是不正确的,因为OP说:“如果容器的所有值都等于给定值(例如None),Python是如何测试的?”
if all(x == value for x in a_dict.values()):