【发布时间】:2015-01-24 05:25:02
【问题描述】:
我最近才开始学习 csv 模块。假设我们有这个 CSV 文件:
John,Jeff,Judy,
21,19,32,
178,182,169,
85,74,57,
我们想要读取这个文件并创建一个字典,其中包含名称(作为键)和每列的总数(作为值)。所以在这种情况下,我们最终会得到:
d = {"John" : 284, "Jeff" : 275, "Judy" : 258}
所以我编写了这段代码,它显然运行良好,但我对它不满意,想知道是否有人知道更好或更高效/优雅的方法。因为那里的行太多了:D(或者也许我们可以概括一下 - 即我们不知道那里有多少字段。)
d = {}
import csv
with open("file.csv") as f:
readObject = csv.reader(f)
totals0 = 0
totals1 = 0
totals2 = 0
totals3 = 0
currentRowTotal = 0
for row in readObject:
currentRowTotal += 1
if currentRowTotal == 1:
continue
totals0 += int(row[0])
totals1 += int(row[1])
totals2 += int(row[2])
if row[3] == "":
totals3 += 0
f.close()
with open(filename) as f:
readObject = csv.reader(f)
currentRow = 0
for row in readObject:
while currentRow <= 0:
d.update({row[0] : totals0})
d.update({row[1] : totals1})
d.update({row[2] : totals2})
d.update({row[3] : totals3})
currentRow += 1
return(d)
f.close()
非常感谢您的任何回答:)
【问题讨论】: