简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM