繁体   English   中英

如何对 Python 中的 csv 文件中的特定值求和?

[英]How to sum specific values in a csv file in Python?

我正在尝试在 CSV 文件中搜索某些条件以及符合该条件的任何内容,以将其打印为总和。

示例数据:

|    city   |  state  |        college         |  cases |
|Huntsville | Alabama | Alabama A&M University |    42  |

等,数百行。 我希望能够搜索数据,例如阿拉巴马州的 state,并将所有等于该 state 的案例相加。

这是我到目前为止所拥有的:

category = input(What would you like to look up? Please enter 'city', 'state', or 'college': ")

if category == "city":
        city = input("Enter a city: ")
        for row in reader:
                if row[0] == city:
                        print("The city of", city, "has had a total of", row[3], "cases at", row[2])
                        print("All cities with the name", city, "have a total of", sum(row[3]), "cases.")

输入的行号对应于我在原始 CSV 文件中需要的行。 所有代码都有效,除了我的最后一行,该行的 sum 命令显然不起作用。 在使用不同的选项时,它不喜欢它是一个字符串变量(即使它是案例的所有数字)。 有一个更好的方法吗? 谢谢你。

您从 csvreader 获得一个数据结构,它可以是列表或字典。 我假设它是一个列表。 简单的方法是:

total = 0
for line in csvdata:
    if line[1] == 'Alabama':
         total += int(line[3])

可以变成列表理解形式

total = sum([int(x[3]) for x in csvdata if x[1] == 'Alabama'])

(更新,感谢您的更正。更正。)

sum(row[3]) ,假设它完全有效,只会返回row[3]这里解释)。 您需要按如下方式更改代码。

category = input(What would you like to look up? Please enter 'city', 'state', or 'college': ")

if category == "city":
    city = input("Enter a city: ")
    sum = 0
    for row in reader:
        if row[0] == city:
            print("The city of", city, "has had a total of", row[3], "cases at", row[2])
            sum += int(row[3])
    print("All cities with the name", city, "have a total of", sum, "cases.")

在您阅读完城市的所有行之前,您不会知道该城市的总数。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM