我有3本字典
demo1={'1':['a','b','c'],'2':['x','y'],...}
demo2={1:['b','c','e'],2:['x','z','w'],...}
coef={'1':5,'2':6,...}
我想要这样的输出
output={1:2/5,2:1/6,...}
其中输出值分子是demo1和demo2之间匹配值的数量,分母是coef中的对应值。
例如对于demo1和demo2中的key = 1,“ b”和“ c”匹配,因此分子为2,key = 1的系数为5
我尝试过通过for循环来实现,但是我有太多循环了,有没有更有效的方法?
PS:demo1中的键是字符串,而demo2中的键是int,输出的返回值无关紧要。字符串或整数都可以
答案 0 :(得分:3)
您可以使用字典理解:
demo1={'1':['a','b','c'],'2':['x','y']}
demo2={1:['b','c','e'],2:['x','z','w']}
coef={'1':5,'2':6}
result = {i:sum(c in demo1[i] and c in demo2[int(i)] for c in set(demo1[i]+demo2[int(i)]))/coef[i] for i in demo1}
输出:
{'1': 0.4, '2': 0.16666666666666666}
答案 1 :(得分:3)
更容易:
print({k:len([i for i in demo1[k] if i in demo2[int(k)]])/v for k,v in coef.items()})
输出:
{'1': 0.4, '2': 0.16666666666666666}
答案 2 :(得分:2)
您可以将值转换为集合并找到相交的长度
{k:len(set(demo1.get(k)).intersection(demo2.get(int(k))))/v for k,v in coef.items()}
{'1': 0.4, '2': 0.16666666666666666}
答案 3 :(得分:2)
output = {len(set(demo1[i]) & set(demo2[int(i)])) / coef[i] for i in demo1}
s1 & s2
是集合s1
和s2
len(s)
将为您提供集合s
中的元素数量答案 4 :(得分:0)
使用合并集的长度
d = {k: len(set(demo1[k]) & set(demo2[int(k)]))/v for k, v in coef.items()}