python - 重新计算Python字典中的值

标签 python list dictionary

我有一个类似的列表

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/

相关文章:

python - 是否可以在 Python 中重载对 vars(object) 的调用?

c# - 如何在 C# 中创建通用列表并使用 Select SQL 查询进行填充

list - 使用通配符比较列表

python - 如何在直方图中绘制字典中的键和值

php - 从服务器python快速下载xml文件

python - python中从下一个时间值中减去上一个时间值

python - Django 和 MongoDB 引擎 - 对象 ID 问题!

python - 从有条件的列表列表中删除列表

c++ - vector 图,坏访问器

python - 如何将具有坐标和频率的字典转换为矩阵?