测试字典的所有值是否相等-当值未知时 [英] Test if all values of a dictionary are equal - when value is unknown

查看:63
本文介绍了测试字典的所有值是否相等-当值未知时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有2个字典: 每个字典中的值应该都相等.
但是,我不知道这个数字是多少...

I have 2 dictionaries: the values in each dictionary should all be equal.
BUT I don't know what that number will be...

dict1 = {'xx':A, 'yy':A, 'zz':A}
dict2 = {'xx':B, 'yy':B, 'zz':B}

N.B. A不等于B
N.B.实际上,A和B都是十进制数字的字符串(例如'-2.304998'),因为它们是从文本文件中提取的

N.B. A does not equal B
N.B. Both A and B are actually strings of decimal numbers (e.g. '-2.304998') as they have been extracted from a text file

我要创建另一个字典-有效地汇总此数据-但前提是每个字典中的所有值都相同.

I want to create another dictionary - that effectively summarises this data - but only if all the values in each dictionary are the same.
i.e.

summary = {}
if dict1['xx'] == dict1['yy'] == dict1['zz']:
    summary['s'] = dict1['xx']
if dict2['xx'] == dict2['yy'] == dict2['zz']:
    summary['hf'] = dict2['xx']

是否有一种整齐的方法可以做到这一点?

Is there a neat way of doing this in one line?

我知道可以使用理解来创建字典
summary = {k:v for (k,v) in zip(iterable1, iterable2)}
但是在底层的for循环和if语句中都遇到了麻烦...

I know it is possible to create a dictionary using comprehensions
summary = {k:v for (k,v) in zip(iterable1, iterable2)}
but am struggling with both the underlying for loop and the if statement...

一些建议将不胜感激.

Some advice would be appreciated.

我看过这个问题,但是答案似乎都依赖于已经知道要测试的值(即字典中的所有条目都等于一个已知数字)-除非我遗漏了什么.

I have seen this question, but the answers all seem to rely on already knowing the value being tested (i.e. are all the entries in the dictionary equal to a known number) - unless I am missing something.

推荐答案

set是进入此处的可靠方法,但仅出于代码高尔夫目的,此版本可以处理不可散列的dict值:

sets are a solid way to go here, but just for code golf purposes here's a version that can handle non-hashable dict values:

expected_value = next(iter(dict1.values())) # check for an empty dictionary first if that's possible
all_equal = all(value == expected_value for value in dict1.values())

all会在不匹配的情况下提前终止,但是set构造函数已进行了充分优化,如果不对真实测试数据进行概要分析,我不会说这很重要.处理非散列值是此版本的主要优点.

all terminates early on a mismatch, but the set constructor is well enough optimized that I wouldn't say that matters without profiling on real test data. Handling non-hashable values is the main advantage to this version.

这篇关于测试字典的所有值是否相等-当值未知时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆