如何获取值(百分比)列表:
example = [(1,100), (1,50), (2,50), (1,100), (3,100), (2,50), (3,50)]并归还一本字典:
example_dict = {1:250, 2:100, 3:150}并通过求和(example_dict.values())/100重新计算:
final_dict = {1:50, 2:20, 3:30} 我尝试将值列表映射到字典的方法会导致值被迭代而不是被求和。
编辑:,因为这里有人问它,这里有一些尝试(在编写了旧值之后)没有去哪里,并演示了我对python的“新手”:
{k: +=v if k==w[x][0] for x in range(0,len(w),1)}无效
for i in w[x][0] in range(0,len(w),1):
for item in r:
+=v (don't where I was going on that one)又无效了。
另一个类似的,是无效的,没有在谷歌上,然后就这样。
发布于 2012-03-15 16:26:29
你可以试试这样的方法:
total = float(sum(v for k,v in example))
example_dict = {}
for k,v in example:
example_dict[k] = example_dict.get(k, 0) + v * 100 / total看到它在网上工作:意为
发布于 2012-03-15 16:27:37
使用Counter类:
from collections import Counter
totals = Counter()
for k, v in example: totals.update({k:v})
total = sum(totals.values())
final_dict = {k: 100 * v // total for k, v in totals.items()}https://stackoverflow.com/questions/9723860
复制相似问题