将每个python字典值除以总值 [英] Divide each python dictionary value by total value

查看:394
本文介绍了将每个python字典值除以总值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有 a = {'foo': 2, 'bar': 3, 'baz': 5 }

反正我可以在一行中得到a = {'foo': 0.2, 'bar': 0.3, 'baz': 0.5 }吗?需要将每个值除以总值...我只是做不完..:(

Is there anyway I can get a = {'foo': 0.2, 'bar': 0.3, 'baz': 0.5 } in one line? Need to divide each value by total value... I just can't get it done.. :(

非常感谢您!

推荐答案

对值求和,然后使用字典推导生成具有标准化值的新字典:

Sum the values, then use a dictionary comprehension to produce a new dictionary with the normalised values:

total = sum(a.itervalues(), 0.0)
a = {k: v / total for k, v in a.iteritems()}

您可以将其压缩为单层,但可读性不强:

You can squeeze that into a one-liner, but it won't be as readable:

a = {k: v / total for total in (sum(a.itervalues(), 0.0),) for k, v in a.iteritems()}

我给了sum()一个浮点起始值,以防止/运算符在Python 2中使用地板分割.如果totalv都为整数,则会发生这种情况.

I gave sum() with a floating point starting value to prevent the / operator from using floor division in Python 2, which would happen if total and v would both be integers.

在Python 3中,删除iter*前缀:

In Python 3, drop the iter* prefixes:

a = {k: v / total for total in (sum(a.values()),) for k, v in a.items()}

请注意,您不想在此处使用{k: v / sum(a.values()) for k, v in a.items()};值表达式在理解循环中的每次迭代中执行,一次又一次地重新计算sum(). sum()遍历字典中的所有N个项目,因此最终得到的是二次O(N ^ 2)解而不是O(N)解.

Note that you do not want to use {k: v / sum(a.values()) for k, v in a.items()} here; the value expression is executed for each iteration in the comprehension loop, recalculating the sum() again and again. The sum() loops over all N items in the dictionary, so you end up with a quadratic O(N^2) solution rather than a O(N) solution to your problem.

这篇关于将每个python字典值除以总值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆