2 回答

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

TA贡献1875条经验 获得超3个赞
一个问题是你不能重复阅读器两次。
模块中的defaultdict类collections对于对项目进行分组很方便。在这里,我们将Prices(Decimal为了精确而转换为s)收集到一个列表字典中,然后将它们相加。
import csv
import decimal
import 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))
添加回答
举报