猿问

如何使用 Python 3.7 汇总数据?

我有我转换成字典的 CSV 文件。字典中的一行看起来像这样:-


OrderedDict([('MVA', '10072672'), ('Code', 'F5'), ('Tbk Mnth', '01-Dec-16'), ('Branch', 'W0S'), ('Make', 'VOLKSWAGENRSA'), ('Status', 'RISK'), ('Price', '111200.27')])

我试图对“价格”列中的值求和,但 n = 0。我做错了什么?另外,总结不同代码的最有效方法是什么?


import csv

linecount = 0

with open(r'C:\Users\anthony\Documents\Test\Data.csv') as file:

    reader = csv.DictReader(file)

    for row in reader:

        print(row)

        code = (row["Code"])

        if code == 'F5':

            linecount += 1


    print(linecount)




    n = sum([item['Price'] for item in reader])

    print(n)


慕妹3242003
浏览 165回答 2
2回答

长风秋雁

reader是一个迭代器。通过迭代它,你可以消耗它的值。如果您需要保留这些值,那么您必须存储在其他地方。最简单的方法是从迭代器创建一个列表,然后迭代这个列表。例如。rows = list(reader)for row in rows:   ...n = sum([item['Price'] for item in rows])但是,价格将是一个字符串而不是一个浮点数。因此,您将列表理解将它们转换为浮点数。例如。float(item['Price'])

翻过高山走不出你

一个问题是你不能重复阅读器两次。模块中的defaultdict类collections对于对项目进行分组很方便。在这里,我们将Prices(Decimal为了精确而转换为s)收集到一个列表字典中,然后将它们相加。import csvimport decimalimport collections# Defaultdicts are handy in that they never have nonexistent keys;# if you access an nonexistent key, the constructor (`list` here)# is invoked.prices_by_code = collections.defaultdict(list)with open(r'Data.csv') as file:    reader = csv.DictReader(file)    for row in reader:        price = row.get('Price')        code = row.get('Code')        if code and price:            prices_by_code[code].append(decimal.Decimal(price))# By this time,  `prices_by_code` looks approximately like# {"5": [1, 2, 3], "8": [4, 5, 6]}for code, prices in sorted(prices_by_code.items()):    print(code, sum(prices))
随时随地看视频慕课网APP

相关分类

Python
我要回答