【问题标题】:How to test the value of all items in a container?如何测试容器中所有项目的价值?
【发布时间】: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


    【解决方案1】:

    如果您添加generator expression,您仍然可以使用all

    if all(x is None for x in a_dict.values()):
    

    或者,任意值:

    if all(x == value for x in a_dict.values()):
    

    【讨论】:

    • 不应该是x is not None和例子中的carry_on一致吗?
    • 我认为该示例不正确,因为 OP 说:“测试容器的所有值是否等于到给定值的 Python 方法是什么(比如无)?”
    猜你喜欢
    • 2013-04-27
    • 2016-08-17
    • 2023-04-07
    • 2022-12-01
    • 2014-12-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-16
    相关资源
    最近更新 更多