[英]How to compare two dictionaries with list values?
Two dictionaries i'm using have the same key.我正在使用的两个字典具有相同的键。 They have lists as value.
他们有列表作为价值。 So example
所以例子
a={'Q':[0, 0, 0], 'T'=[6, 0, 0, 0]......}
b={'Q':[0, 0], 'T'=[0, 6, 0, 0]........}
I have to check how many values match out of the two.我必须检查两者中有多少值匹配。 I did this
我做了这个
def shared_keyvals(dict1, dict2):
return dict( (key, dict1[key])
for key in (set(dict1) & set(dict2))
if dict1[key] == dict2[key]
)
but it does not compare T=[6,0,0,0] same as T=[0,6,0,0].但它不会比较 T=[6,0,0,0] 与 T=[0,6,0,0] 相同。
So ultimately I want to calculate the no.values b got same as a.所以最终我想计算与 a 相同的 no.values b。 So for this example no.of values same of a and b would be 6 (out of 7)
所以对于这个例子,a 和 b 相同的值的数量为 6(共 7 个)
This works:这有效:
def compare(a, b):
"""Compare two lists and add up the number of matching elements."""
a.sort()
b.sort()
if len(a) > len(b): # make a the shorter list
a, b = b, a
count = 0
for i in range(len(a)):
if a[i] == b[i]:
count += 1
return count
a={'Q':[0, 0, 0], 'T':[6,0,0,0]}
b={'Q':[0, 0], 'T':[0, 6, 0, 0]}
dictionary = {key : compare(a[key], b[key]) for key in a.keys()}
# {'Q': 2, 'T': 4}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.