csv列表比较和加法

csv列表比较和加法

解析和添加客户端数据

Data:
('Client 1', '13.2')
('Client 1', '22.4')
('Client 1', '1.2')
('Client 2', '3.4')
('Client 3', '12.3')
('Client 3', '3.221')
('Client 4', '234.44')

尝试编写正确的循环并添加功能以获得正确的输出。

目标结果:

客户端 1:36.8
客户端 2:3.4
客户端 3:15.521
客户端 4:234.44

这是我最终正确列出数据的代码。我从这里去哪里得到结果。我尝试了许多不同的循环,但都没有成功。
import csv

with open('clientdata.csv') as csvfile:
    reader = csv.DictReader(csvfile)
    numbers = []
    for row in reader:
       print(row['Client Name'], row['Earnings'])

最佳答案

您可以通过使用格式字符串(%.2f 将有 2 个小数位)和记录谁赚多少钱的字典来解决它。

clients = {}
with open('clientdata.csv') as csvfile:
    reader = csv.DictReader(csvfile)
    numbers = []
    for row in reader:
       name = row['Client Name']
       earnings = float(row['Earnings'])
       if name in clients:
           clients[name] += earnings
       else:
           clients[name] = earnings
    for client in sorted(clients):
          print("%s:%.2f" % (client, clients[client]))

关于python csv列表比较和加法,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/34888005/

10-12 19:55