如何使用Python打印txt文件中的姓名且避免出现重复内容
解决方案
利用Python集合(set)自动去重的特性即可实现需求,修改后代码如下:
# 存储已出现过的姓名 used_names = set() # 用with语句打开文件,自动管理资源 with open("Nombres.txt", "r", encoding="utf-8") as f: for line in f: current_name = line.rstrip() # 跳过空行,不需要可以删除 if not current_name: continue # 仅当姓名未出现过时打印并记录 if current_name not in used_names: used_names.add(current_name) print(current_name)
原理说明
- 集合的元素具有唯一性,天然不允许重复值存在,刚好匹配去重需求
with语句会在代码块执行结束后自动关闭文件,不需要手动调用close()方法,避免文件资源泄漏- 如果存在大小写不同但视为同一姓名的场景(比如
Lily和lily算同一个),可以把current_name改为current_name.lower()再做判断和存储
内容的提问来源于stack exchange,提问作者Victotem
相关产品推荐
相关产品推荐

