You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求助:编写实现首都转「首都,国家代码」格式的Python脚本

解决首都转「首都名称,国家两位字母代码」的脚本问题

你的代码逻辑框架没问题,但存在几个关键问题导致无法正常输出结果,同时可以做一些优化适配需求:

原代码的核心问题

  1. 没有输出最终拼接后的结果
  2. 未将国家代码转为小写(不符合示例中uk、es的格式)
  3. 对于批量处理场景效率较低

修正后的单输入版本代码

import pycountry

capital = input("Capital city: ").strip()
country_code = None

for country in pycountry.countries:
    # 直接判断是否存在capital属性,替代try-except更直观
    if hasattr(country, 'capital') and country.capital:
        if country.capital.lower() == capital.lower():
            country_code = country.alpha_2.lower()
            break

# 输出最终结果或提示未找到
if country_code:
    print(f"{capital},{country_code}")
else:
    print(f"未找到首都 {capital} 对应的国家代码")

批量处理优化版本(适配首都列表需求)

如果需要处理批量首都名称,预构建映射字典能大幅提升效率:

import pycountry

# 提前构建首都→国家代码的映射表,统一转小写避免大小写匹配问题
capital_code_map = {}
for country in pycountry.countries:
    if hasattr(country, 'capital') and country.capital:
        capital_key = country.capital.lower()
        capital_code_map[capital_key] = country.alpha_2.lower()

# 示例首都列表
capital_list = ["London", "Madrid", "Paris", "Tokyo"]

# 批量处理输出
for cap in capital_list:
    clean_cap = cap.strip().lower()
    code = capital_code_map.get(clean_cap)
    if code:
        print(f"{cap},{code}")
    else:
        print(f"未找到首都 {cap} 对应的国家代码")

额外说明

注意你示例中的Barcelona并不是西班牙的首都(西班牙首都是Madrid),因此用该名称测试会返回"未找到",这是数据匹配问题而非代码问题。

内容的提问来源于stack exchange,提问作者suer231232131133

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.26 04:23:23