我有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的coef为5
我试过通过 for 循环来完成,但是我有太多循环,有没有更有效的方法?
PS:demo1 中的key 是string,demo2 中的key 是int,输出返回什么并不重要。 string 或 int 都可以
最佳答案
你可以使用字典理解:
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}
关于python - 基于键对少数字典的操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52508552/