在python中读取CSV文件并求和th中的值

2024-05-18 01:00:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图解决以下问题:

Complete the function sumRows so that it reads a file of this format and returns a dictionary whose keys specify the names and whose values are the sum of numerical values in the corresponding row. For example, the record above would result in an entry 'dave': 14.0. Empty or non-numerical fields (other than the names in the first column) should be ignored.

我下面的代码尝试似乎不起作用,我不确定我完全理解这个问题。在

def sumRows(filename, header=False):
    d ={}
    with open(filename) as csvfile:
        headerline = csvfile.next()
        total = 0
        for row in csv.reader(csvfile):
            total += int(row[1])
        print(total)

对于csv文件

rows1

dave,3,5,6
tina,12,3,5


Tags: andofcsvthecsvfileinnamesnumerical
1条回答
网友
1楼 · 发布于 2024-05-18 01:00:05

代码中的第一个问题是:

headerline = csvfile.next()

Python中的迭代器(文件、CSV读取器等)没有next方法。*有一个^{} function将迭代器作为参数,如下所示:

^{pr2}$

如果我修复了这个问题,您的代码将输出第二列中所有值的总和。在

但你应该求和行数,而不是列数。在

要解决此问题,需要迭代每行的列:

    for row in csv.reader(csvfile):
        rowtotal = 0
        for column in row[1:]:
            rowtotal += int(column)
        print(row[0], rowtotal)    

现在我们越来越近了,但你还有四个问题需要解决。在

  • “空的或非数字的字段…应该被忽略”,但是你的代码没有这样做,它会引发一个ValueError。因此,您需要try将每个列转换为int,并以适当的方式处理可能的{}。

  • 这个问题问的是“数字”,而不是“整数”,并以14.0为例。所以int可能不是正确的类型。您可能需要float或{}。有关详细信息,请参见教程中的Numbers

  • 你不应该只打印出每一个名字和行和,你应该把它们放在字典里,然后返回字典。你通过做d[key] = value把一些东西放到字典里,所以希望你能想出如何把名字和行和放入你的d。最后return d

  • 由于某种原因,header=False参数必须存在。我的猜测是,你应该使用它让调用者指定是否有要跳过的标题行,而不是不管发生什么都总是跳过标题行。所以,你需要一个if header:的地方。


*这只适用于python3.x,但这正是您所使用的。如果不是,那么您可能使用的是2.7,其中迭代器有一个next方法,但您仍然不应该调用它。

相关问题 更多 >