我有一个类似的列表
result =[{'a': 5}, {'b': 4}, {'c': 3}, {'ar': 10}, {'ade': 10}]
现在我想重述一下这些词典的值(value)。例如,'a' 是 'ar'
和 len(a)/len(ar)=1/2
的子串,因此 {'a':5 }
转向 {'a':5+10/2}
。
另外, 'a' 是 'ade' 的子字符串,并且 len(a)/len(ade)=1/3 。最后,它应该是 {'a': 5+10/2+10/3} 。那么如何在不使用for方法的情况下解决这个问题呢?
我发现我可以在上一步中将这个结果转为字典,但我仍然需要使用 for 方法。
最佳答案
预期输出不清楚(“ar”与“ade”?),但我建议使用 defaultdict来自collections ,这样:
from collections import defaultdict
result =[{'a': 5}, {'b': 4}, {'c': 3}, {'ar': 10}, {'ade': 10}]
res = defaultdict(list)
for h in result:
key = list(h.keys())[0]
val = list(h.values())[0]
key_f = key[0]
size = len(key)
print(size)
res[key_f].append(val/size)
此步骤产生:
defaultdict(<class 'list'>, {'a': [5.0, 5.0, 3.3333333333333335], 'b': [4.0], 'c': [3.0]})
然后迭代将值转换为列表的总和:
for k, v in res.items():
res[k] = sum(v)
print(dict(res))
#=> {'a': 13.333333333333334, 'b': 4.0, 'c': 3.0}
关于python - 重新计算Python字典中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57106829/