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

如何用Set避免Python文本文件拆分后出现重复输出?

问题:去除错误码与颜色组合的重复输出

问题描述

我有一个文本文件,已将其内容按行读取并拆分,确认拆分后的列表中s[3]为错误码、s[7]为颜色结果。但目前输出中存在重复的错误码与颜色组合,我希望仅显示每组组合的唯一实例。我尝试使用Set实现去重,但不知具体方法。

当前代码:

f = open("textfile.txt", "r")
error = f.readlines()
for l in error:
    s = l.split()
    if "70" in s[3]:
        print("Error:", s[3], "Color:", s[7])
f.close()

当前输出:

Error: 701 Color: Purple
Error: 701 Color: Purple
Error: 702 Color: Pink
Error: 702 Color: Pink
Error: 702 Color: Pink
Error: 705 Color: Black
Error: 705 Color: Black
Error: 705 Color: Black
Error: 705 Color: Black

期望输出:

Error: 701 Color: Purple
Error: 702 Color: Pink
Error: 705 Color: Black

解决方案

利用Python的set自动去重的特性,通过记录已输出的错误码+颜色组合来实现需求:

  1. 初始化一个空集合seen,用于存储已经处理过的组合
  2. 遍历每行数据时,生成由错误码和颜色组成的元组(元组可哈希,能存入集合)
  3. 若该组合未在集合中,则打印结果并将组合加入集合;已存在则跳过

修改后的代码

f = open("textfile.txt", "r")
error = f.readlines()
seen = set()  # 存储已出现的组合
for l in error:
    s = l.split()
    if "70" in s[3]:
        combo = (s[3], s[7])
        if combo not in seen:
            seen.add(combo)
            print("Error:", s[3], "Color:", s[7])
f.close()

更优写法(自动关闭文件)

推荐使用with语句管理文件,无需手动调用close(),代码更安全简洁:

seen = set()
with open("textfile.txt", "r") as f:
    for l in f:
        s = l.split()
        if "70" in s[3]:
            combo = (s[3], s[7])
            if combo not in seen:
                seen.add(combo)
                print("Error:", s[3], "Color:", s[7])

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 17:01:07