Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
83 views
in Technique[技术] by (71.8m points)

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
question from:https://stackoverflow.com/questions/65839482/sort-a-list-from-a-file

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
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 :)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...