如何用Python实现无冗余字典的城市归属查询程序?
Python基础编程题优化:城市所属国家查询
题目背景
我正在准备Python基础编程考试,这是一道备考练习题:
文件
countries.txt中每行包含一个国家名称及其所属城市,示例如下:USA Boston Pittsburgh Washington Seattle UK London Edinburgh Cardiff Belfast编写程序循环提示用户输入城市名称,输出该城市所属国家;若输入未提及的城市,输出“No information about the city ...”;输入“done”则终止程序。程序输出示例如下:
Please enter the name of a city: Cardiff Cardiff is in UK Please enter the name of a city: Seattle Seattle is USA Please enter the name of a city: Moscow No information about Moscow Please enter the name of a city: London London is in UK Please enter the name of city: done
原始解法及问题
我最初的代码实现如下:
handle = open('countries.txt') pair = dict() for line in handle: line = line.split() for word in line: pair[word] = line[0] while True: city = input('Enter city: ') if city in pair: print(pair[city]) elif city == 'done': break elif city not in pair: print('No info') handle.close()
但这个方案存在明显问题:生成的字典包含冗余键值对(比如'USA':'USA'),示例字典如下:
pair = {'USA': 'USA', 'Boston': 'USA', 'Pittsburgh': 'USA', 'Washington': 'USA', 'Seattle': 'USA', 'UK': 'UK', 'London': 'UK', 'Edinburgh': 'UK', 'Cardiff': 'UK', 'Belfast': 'UK'}
这些冗余键值对完全无用,而且用户输入国家名时会返回自身,不符合题目仅处理城市查询的要求。请问该如何解决?字典是不是并非最优方案?
优化方案
1. 修正字典构建逻辑,消除冗余
问题核心是遍历整行元素时错误地将国家名也作为键存入了字典。只需要把每行第一个元素作为国家,后续元素作为城市,仅将城市作为键存入字典即可:
with open('countries.txt', 'r') as handle: city_to_country = {} for line in handle: parts = line.strip().split() if not parts: # 跳过空行,增强鲁棒性 continue country = parts[0] # 仅遍历该行从第二个元素开始的城市 for city in parts[1:]: city_to_country[city] = country while True: city = input('Please enter the name of a city: ') if city == 'done': break if city in city_to_country: print(f'{city} is in {city_to_country[city]}') else: print(f'No information about {city}')
同时做了这些细节优化:
- 使用
with语句自动管理文件资源,避免手动关闭文件的遗漏 - 处理空行,防止因文件格式问题报错
- 输出格式完全匹配题目示例要求
2. 字典仍是最优选择
字典是处理这类键值查询场景的最优方案,因为字典的成员判断和取值操作时间复杂度均为O(1),无论数据量多大,查询效率都很高。如果改用列表存储(城市, 国家)元组,每次查询都需要遍历整个列表,时间复杂度为O(n),数据量大时效率会显著下降。
3. 自动规避国家名输入问题
优化后的字典中仅包含城市作为键,当用户输入国家名时,会直接触发“无信息”的输出,完全符合题目仅处理城市查询的要求,无需额外判断。
内容的提问来源于stack exchange,提问作者Tommaso Maganzani
相关产品推荐
相关产品推荐

