[英]python printing total result from file by only printing every name once?
Hi I'm trying to print some information from a file to get the names of the person only to show up once with all the numbers of the person added together. 嗨,我正在尝试从文件中打印一些信息,以获取此人的名字,而该人的所有号码加在一起仅显示一次。
The information from the file looks something like this: randomfile.txt 文件中的信息如下所示:randomfile.txt
Jack, 20.00
Sofie, 12.00
Jack, 32.50
Sofie, 33.75
The output I want: 我想要的输出:
Jack 52.50
Sofie 45.75
I know how to get all the information but I don't know how to get the information added up so that I can print it without having to print the names multiple times. 我知道如何获取所有信息,但是我不知道如何将信息加起来,这样我就可以打印它而不必多次打印名称。
Simple approach. 简单的方法。
scores = {}
for line in txtfile:
name, score = line.split(",")
if name in scores:
scores[name] += score
else:
scores[name] = score
for k,v in scores.items():
print(k,v)
You still have some tweaks to do here... I'll leave those to you 您仍然可以在这里进行一些调整...我将这些留给您
Here's a simple way of doing it. 这是一种简单的方法。
s = '''Jack, 20.00
Sofie, 12.00
Jack, 32.50
Sofie, 33.75'''
final_dict = {}
for line in s.split('\n'):
name = line.split(',')[0].strip()
score = line.split(',')[1].strip()
if name in final_dict.keys():
final_dict[name] = float(final_dict[name]) + float(score)
else:
final_dict[name] = float(score)
for k, v in final_dict.items():
print(k,'',v)
Outputs: 输出:
Jack 52.5
Sofie 45.75
我将把它留在这里只是为了好玩:
awk '{p[$1] += $2} END {for (k in p) print k" "p[k]}' randompeople.txt
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.