簡體   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