我想从python中的库CountryInfo中获取一个国家列表的人口

2024-09-30 12:20:45 发布

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

我可以通过以下方式从CountryInfo中提取一个国家的信息:

from countryinfo import CountryInfo
country = CountryInfo('India')
country.info()

以及

country.population()

然而,我有一系列的国家,比如

country = ['Afganistan', 'India', 'Zimbabwe']

我想遍历库CountryInfo,根据country数组得到每个国家的人口,并将其保存在数组中


Tags: fromimportinfo信息方式数组国家country
2条回答

您要求提供一个“数组”(您是指列表吗?),但将数据保存在字典中更有意义:

from countryinfo import CountryInfo

populations = {}

for country_name in ['Afghanistan', 'India', 'Zimbabwe']: 
    country = CountryInfo(country_name)
    populations[country_name] = country.population()

print(populations)

这给了你

{'Afghanistan': 26023100, 'India': 1263930000, 'Zimbabwe': 13061239}

然后你可以做个例子

print(populations["Zimbabwe"])  # prints 13061239

根据我的假设并理解您的答案,这里是工作示例代码

from countryinfo import CountryInfo

country = ['Afghanistan', 'India', 'Zimbabwe']

for c in country:
    country = CountryInfo(c)
    country.info()
    print("Country :" + c + " population:" + str(country.population()))

enter image description here

相关问题 更多 >

    热门问题