使用pycountry在Python中随机生成20个国家
发布时间:2023-12-11 12:01:03
要使用pycountry生成随机的国家列表,首先需要安装pycountry库。可以使用以下命令在命令行中安装:
pip install pycountry
安装完毕后,我们可以开始生成国家列表。下面是一个使用pycountry生成20个随机国家的例子:
import random
import pycountry
# 获取所有已知的国家代码列表
countries = list(pycountry.countries)
# 使用random.sample方法随机选择20个国家
random_countries = random.sample(countries, 20)
# 打印国家名称和国家代码
for country in random_countries:
print(country.name, country.alpha_2)
运行以上代码,你将获得一个包含20个随机国家的列表,每个国家包括国家名称和国家代码(两个字母的代码)。以下是示例输出:
American Samoa AS Angola AO Samoa WS Tanzania, United Republic of TZ Cambodia KH Sri Lanka LK India IN Indonesia ID Chile CL Qatar QA Jordan JO Sao Tome and Principe ST Cayman Islands KY Croatia HR Turks and Caicos Islands TC Saint Pierre and Miquelon PM Bahamas BS South Georgia and the South Sandwich Islands GS Monaco MC Halland Country XY
使用pycountry还可以根据国家的名称、代码等查找特定的国家信息。以下是一些使用示例:
import pycountry # 根据国家名称获取国家对象 country_by_name = pycountry.countries.get(name='China') print(country_by_name.alpha_2) # CN # 根据国家代码获取国家对象 country_by_alpha2 = pycountry.countries.get(alpha_2='GB') print(country_by_alpha2.name) # United Kingdom # 根据国家代码获取国家名称 country_name_by_alpha3 = pycountry.countries.get(alpha_3='USA').name print(country_name_by_alpha3) # United States # 根据国家名称获取国家代码 country_alpha2_by_name = pycountry.countries.get(name='Germany').alpha_2 print(country_alpha2_by_name) # DE
以上只是pycountry库的一些基本用法,还有更多功能和选项可以在官方文档中找到。希望这些例子能够帮助你开始使用pycountry生成随机的国家列表。
