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

如何高效检测文本文件中重复的login:password子串?

高效检测并去重文件中重复的login:password条目

你的原代码采用嵌套循环检查已存储条目,时间复杂度为O(n²),处理1万行数据时会产生近1亿次循环操作,这是导致耗时过长的核心原因。

优化思路

用**集合(set)**存储已出现过的login:password对——集合的成员查找操作时间复杂度为O(1),能将整体处理效率提升至O(n),同时内存占用也更低。

优化后代码

seen_accounts = set()
output_lines = []

# 读取文件并去重
with open('path/file.txt', 'r') as f:
    for line in f:
        line = line.strip()
        if not line:
            continue  # 跳过空行
        # 提取login:password部分
        parts = line.split(':')
        if len(parts) < 2:
            output_lines.append(line + '\n')  # 格式异常的行直接保留
            continue
        account_key = f"{parts[0]}:{parts[1]}"
        if account_key not in seen_accounts:
            seen_accounts.add(account_key)
            output_lines.append(line + '\n')

# 写入去重后的内容覆盖原文件
with open('path/file.txt', 'w') as f:
    f.writelines(output_lines)

额外优化点

  • 逐行读取:避免一次性加载全量文件到内存,处理超大文件(比如100万行+)时更友好
  • 格式异常处理:对分割后字段不足2个的行直接保留,避免程序崩溃
  • 空行过滤:可根据需求选择是否保留空行,示例中跳过空行

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 22:22:13