字典相等.

我有一个查询字段列表:


>>> l = ['A', 'C', 'Z', 'M']

我将需要在此查找列表上测试2个词典的相等性:


>>> d1 = {'A': 3,'F': 4,'Z': 1}

>>> d2 = {'B': 0,'A': 3,'C': 7}

如果满足以下任一条件,则对列表中任何字段'x'的相等性测试成功:1.如果

两个字典中

都不存在'x'2.如果'x'存在并且d1 [x] = = d2 [x]


仅当根据上述条件,列表中的所有字段都成功时,equity函数才返回匹配项。


因此,对于上述命令-Z失败,C失败,A成功,M成功。

但是,对字典的相等性测试应报告失败。


实现这一目标的最短方法是什么?


DIEA
浏览 165回答 3
3回答

互换的青春

您可以使用all:>>> from itertools import chain>>> l = ['A', 'C', 'Z', 'M']>>> d1 = {'A': 3,'F': 4,'Z': 1}>>> d2 = {'B': 0,'A': 3,'C': 7}>>> all( x not in chain(d1,d2) or ((x in d1 and x in d2) and \                                            d1.get(x) == d2.get(x))  for x in l)False>>> l = ['Z']>>> d1 = {'A': 3,'F': 4,'Z': None}>>> all( x not in chain(d1,d2) or ((x in d1 and x in d2) and  \                                            d1.get(x) == d2.get(x))  for x in l)Falseall将返回True只有在迭代的所有值都Trueothwerwise它会返回False。

慕田峪7331174

尝试这个:success = Truefor x in l:  if not (((x not in d1) and (x not in d2)) or (d1.get(x) == d2.get(x))):    success = False
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python