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

2024-05-15 12:21:18 发布

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

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

示例数据:

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

等等,上百行。我希望能够搜索数据,例如,阿拉巴马州,并汇总所有与该州相等的案例

这就是我到目前为止所做的:

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命令显然不起作用。当使用不同的选项时,它不喜欢它是一个字符串变量(即使它是所有案例的数字)。有更好的方法吗?多谢各位


Tags: 文件ofcsv数据cityinputif条件
2条回答

sum(行[3]),假设它能正常工作,将返回行[3](解释here)。您需要按如下方式更改代码

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.")

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

您将从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'])

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

相关问题 更多 >