python - Sort a list from a file
问题描述
I have an excel file that contains the following entry like:
A 10
B 30
C 20
A 20
B 15
Using python scripting how can I get the desired output, like the sum of all the similar values :
A 30
B 45
C 20
解决方案
d = dict()
for letter, number in line:
d[letter] = number + d.get(letter, 0)
for x in sorted(d.keys()):
print(x, d[x])
The second param in d.get
gives a default value of 0
if letter
is not already in the dictionary.
The sorted()
func makes sure you are going in incr order wrt to keys.
We have a cumulative mapping and then print it out, short and sweet :)
推荐阅读
- windows - 我不能用 python 播放音频
- android - 当我按下返回时,如何刷新 recylverview 项目?
- javascript - jquery在单击时将1添加到变量然后插入到数据库
- c - 删除字符串数组中的空格并计算空格 C
- python - 无法从 shopee.com 抓取最畅销的产品
- arrays - 制作一个快速将结构附加到数组的按钮
- c# - 当用户说 y ANYWHERE 时我们如何触发 X
- pandas - Pandas - 如何从多行的值中获取每行的最小值
- azure - Azure Terraform Virtual Vetwork 对等互连错误(对等两个现有 vnet)
- java - Java - PEM 文件中的 RSA 公钥 - java.lang.NoClassDefFoundError: org/bouncycastle/asn1/x509/SubjectPublicKeyInfo