You need to enable JavaScript to run this app. Python中高效定位符号在嵌套子列表中出现位置的实现方法
优惠活动
大模型
产品
解决方案
定价
更多

Python中高效定位符号在嵌套子列表中出现位置的实现方法

高效符号位置统计实现方案

无需提前拼接全量元素去重,单次遍历即可完成符号收集与位置记录,整体时间复杂度为O(N)(N为数据集所有子列表的元素总数),相比原有两步法效率提升约一倍,同时避免大列表拼接的内存开销

实现逻辑

  • 遍历过程中通过字典自动记录出现过的符号,无需提前单独做全量去重
  • 逐元素匹配当前符号的记录状态:
    • 若符号为首次出现,直接新增「(子列表索引, [当前元素位置])」的元组记录
    • 若符号已存在且当前记录属于同一子列表,直接向对应位置列表追加当前元素位置
    • 若符号已存在但属于新的子列表,新增对应子列表的记录元组
  • 遍历完成后直接转换为要求的FinalList格式即可

代码实现

无依赖版本(兼容性更好)

db = [['C','A','G','A','A','G','T'],['T','G','A','C','A','G'],['G','A','A','G','T']]

pos_dict = {}
for sub_idx, sub_list in enumerate(db):
    for pos, char in enumerate(sub_list):
        # 初始化新符号的记录列表
        if char not in pos_dict:
            pos_dict[char] = []
        records = pos_dict[char]
        # 同一子列表内直接追加位置,否则新增子列表记录
        if records and records[-1][0] == sub_idx:
            records[-1][1].append(pos)
        else:
            records.append((sub_idx, [pos]))

# 转换为要求的输出格式
FinalList = [(char, records) for char, records in pos_dict.items()]

标准库优化版本

from collections import defaultdict

db = [['C','A','G','A','A','G','T'],['T','G','A','C','A','G'],['G','A','A','G','T']]

pos_dict = defaultdict(list)
for sub_idx, sub_list in enumerate(db):
    for pos, char in enumerate(sub_list):
        if pos_dict[char] and pos_dict[char][-1][0] == sub_idx:
            pos_dict[char][-1][1].append(pos)
        else:
            pos_dict[char].append((sub_idx, [pos]))

FinalList = [(char, records) for char, records in pos_dict.items()]

运行结果说明

执行上述代码后得到的FinalList完全匹配实际数据集的统计逻辑:

[
 ('C', [(0, [0]), (1, [3])]),
 ('A', [(0, [1, 3, 4]), (1, [2, 4]), (2, [1, 2])]),
 ('G', [(0, [2, 5]), (1, [1, 5]), (2, [0, 3])]),
 ('T', [(0, [6]), (1, [0]), (2, [4])])
]

注:用户示例中A在0号子列表的位置标注为[1,2,4]为笔误,实际对应给定db的元素,A的位置为[1,3,4],代码输出为正确统计结果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.19 22:45:08