定义lookup_country_iso_codes函数遇AssertionError,请求问题排查
问题排查:lookup_country_iso_codes函数返回(None, None)的错误
问题场景
需要实现函数lookup_country_iso_codes,根据国家名称返回2位和3位ISO代码,依赖工作目录下的countries.json文件。测试时出现错误:
AssertionError: Tuples differ: (None, None) != ('TW', 'TWN')
函数预期示例:
def lookup_country_iso_codes(country: str) -> tuple: """ >>> lookup_country_iso_codes("Taiwan") ('TW', 'TWN') >>> lookup_country_iso_codes("Japan") ('JP', 'JPN') >>> lookup_country_iso_codes("Lithuania") ('LT', 'LTU') >>> lookup_country_iso_codes("Slovenia") ('SI', 'SVN') """
countries.json部分结构:
[{ "name" : "Afghanistan", "iso2": "AF", "iso3" : "AFG", "numeric": "004" }, { "name" : "South Africa", "iso2": "ZA", "iso3" : "ZAF", "numeric": "710" }, { "name" : "Åland Islands", "iso2": "AX", "iso3" : "ALA", "numeric": "248"}]
用户编写的代码:
import json def lookup_country_iso_codes(country: str) -> tuple: with open('countries.json', 'r', encoding='utf-8') as file: countries_data = json.load(file) if country.strip().lower() == "taiwan": return 'TW', 'TWN' for entry in countries_data: if entry['name'].strip().lower() == country.strip().lower(): return entry.get('alpha2Code'), entry.get('alpha3Code') return None, None
错误原因
- 键名不匹配:代码中使用
alpha2Code和alpha3Code作为获取ISO代码的键,但countries.json文件中对应的键是iso2和iso3,导致entry.get()无法找到对应值,返回None。 - 台湾分支逻辑冗余:当前代码先读取文件再判断台湾,存在不必要的IO操作;测试中返回
(None, None)的核心原因还是键名错误。
修复后的代码
import json def lookup_country_iso_codes(country: str) -> tuple: # 归一化输入的国家名称,避免重复处理 normalized_country = country.strip().lower() # 优先处理台湾的特殊情况,无需读取文件 if normalized_country == "taiwan": return ('TW', 'TWN') # 读取国家数据文件 with open('countries.json', 'r', encoding='utf-8') as file: countries_data = json.load(file) for entry in countries_data: if entry['name'].strip().lower() == normalized_country: # 使用JSON文件中实际存在的键名 return (entry.get('iso2'), entry.get('iso3')) return (None, None)
关键修改点
- 将获取ISO代码的键名从
alpha2Code/alpha3Code改为iso2/iso3,与JSON文件结构匹配 - 提前计算归一化后的国家名称,减少重复调用
strip().lower()的开销 - 调整台湾判断逻辑的位置,避免不必要的文件读取操作
内容的提问来源于stack exchange,提问作者a951443
相关产品推荐
相关产品推荐

