Dictreader没有按预期工作

时间:2015-11-21 15:27:06

标签: python csv python-3.x

def sumColumns(filename):
    from csv import DictReader
    with open(filename) as f:
        a1=[row["bob"] for row in DictReader(f)] # I want this part to extract every
        a2=[row["anna"] for row in DictReader(f)]# column into a list and be put into
        a3=[row["tim"] for row in DictReader(f)] # variables. It only works for a1.
        dic={}
        total1=0
        total2=0
        total3=0
        for i in a1:
            total1 = total1 + float(i)
        dic["bob"] = total1 # adding the name of the person with the number into a dict
        for i in a2:
            total2 = total2 + float(i)
        dic["anna"] = total2
        for i in a3:
            total3 = total3 + float(i)
        dic["tim"] = total3
        return dic

我的问题是此代码仅适用于“a1”变量,其他2个代码返回0,因此我的最终结果为{'bob': 41.0, 'anna': 0, 'tim':0}

我不知道如何解决这个问题。在此之前,我尝试了zip()函数但仍然返回错误。

以下是想要下载它的人的csv文件:

http://tempsend.com/0D1ED483C3

对于那些不喜欢下载文件的人来说,这是一张它看起来如何的图片:

Image of csv file

1 个答案:

答案 0 :(得分:1)

您正试图从同一个文件重新读取,但忘记了倒带'文件。当您从文件中读取文件时,文件具有当前文件位置;在到达结束后尝试读取然后导致根本没有读取数据。

您可以使用f.seek(0)每次将文件位置重新开始,但不是从文件中读取3次,您应该阅读一次并重复使用以下信息:< / p>

with open(filename) as f:
    rows = list(DictReader(f))
    a1 = [row["bob"] for row in rows]
    a2 = [row["anna"] for row in rows]
    a3 = [row["tim"] for row in rows]

您可以在此处使用sum()功能:

with open(filename) as f:
    rows = list(DictReader(f))
    dic['bob'] = sum(float(r['bob']) for r in rows)
    dic['anna'] = sum(float(r['anna']) for r in rows)
    dic['tim'] = sum(float(r['tim']) for r in rows)

或使用名称为的循环:

with open(filename) as f:
    rows = list(DictReader(f))
    for name in ('bob', 'anna', 'tim'):
        dic[name] = sum(float(r[name]) for r in rows)