如何从 python 中的多个 for 循环添加数字?

How do I add numbers from multiple for loops in python?

helpp.json

{
"States":{
    "Illinois":{
        "county":[
            {
             "population":100000,
             "nameofcounty":"Dupage"   
            },
            {
                "population":200000,
                "nameofcounty":"Marion"   
               }
        ]
    },
    "Indiana":{
        "county":[
            {
             "population":100000,
             "nameofcounty":"Dupage"   
            },
            {
                "population":200000,
                "nameofcounty":"Marion"   
               }
        ]
    }
}
}

我的代码

import json

with open('helpp.json') as file: 
    package_json = json.load(file)
IN = package_json['States']['Illinois']['county']
IL = package_json['States']['Indiana']['county']

for i in IN:
    county = i['nameofcounty']
    population = i['population']
for j in IL:
    population = j['population']
    county = j['nameofcounty']

    total_population = i['population']+j['population']
    print(county,total_population)

我不知道如何正确地从多个 for 循环中添加数字。我当前的输出是 Dupage 300000 Marion 400000 但它应该是 Dupage 200000 马里昂 400000.

您在代码中犯的简单错误是倒数第二行,其中您添加了 i['population'] 和 j['population'。此处,第一个 for 循环已退出,因此代码将 i 的最后一个值设为 200000 (Marion 的人口数)。因此,为防止此错误,您首先可以使用不同的名称,因为我真的不知道为什么要为具有相同变量的 2 个不同数据集定义 2 次不同的人口。以下是您可以通过它的一些方法:

import json
with open('test.json') as file: 
    package_json = json.load(file)
IN = package_json['States']['Illinois']['county']
IL = package_json['States']['Indiana']['county']

for i in IN:
    county = i['nameofcounty']
    population = i['population']
    for j in IL:
        population_1 = j['population']
        county_1 = j['nameofcounty']
        if county_1 == county: #To check if they are the same thing
            total_population = population_1+population #adds them
            print(county, total_population) #Print

然而,上述方法效率不高。我个人建议尝试:

import json    
with open('test.json') as file: 
    package_json = json.load(file)
IN = package_json['States']['Illinois']['county']
IL = package_json['States']['Indiana']['county']

for i,j in zip(IN,IL): #zip() basically makes it combined
    print(i['nameofcounty'],i['population']+j['population'])

两者的输出相同,但第二个在您的情况下效率更高。有关 zip() 的更多信息,您可以查看 docs