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 Marion 400000。
uj5u.com熱心網友回復:
您在代碼中所做的簡單錯誤是倒數第二行,您將 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() 的更多資訊,您可以查看檔案
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/444156.html
