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

Python如何统计元组列表中的重复字符串并检测区间重叠

功能实现:区间重叠+重复字符串检测

需求背景

需要对存储了区间起止值、关联字符串的元组列表,同时完成两类检测:

  • 区间重叠检测(已有基础实现)
  • 列表内关联字符串的重复检测与计数

测试数据集

ls = [(100, 350,"a"), (125, 145,"a"), (200, 400, "d"), (0, 10, "a")]

已有区间重叠检测代码

def overlap(a, b) -> bool:
  a_start, a_end, _ = a
  b_start, b_end, _ = b
  return a_start < b_end and b_start < a_end

overlaps = set()
for idx_a in range(len(ls)):
    for idx_b in range(len(ls)):
        if idx_a != idx_b:  
            if overlap(ls[idx_a], ls[idx_b]):
                overlaps.add(ls[idx_a])
                overlaps.add(ls[idx_b])

print(f"存在重叠的区间条目数: {len(overlaps)}")

补充:重复字符串检测计数实现

实现逻辑

遍历所有元组提取第三个位置的关联字符串,通过字典统计每个字符串的出现频次,出现次数大于1的即为重复字符串,可同时输出重复字符串的出现次数、关联的所有区间条目。

  • 无额外依赖写法:如果不想导入collections模块,可以用普通字典实现相同统计逻辑,不需要额外导入包。

完整整合代码

def overlap(a, b) -> bool:
  a_start, a_end, _ = a
  b_start, b_end, _ = b
  return a_start < b_end and b_start < a_end

ls = [(100, 350,"a"), (125, 145,"a"), (200, 400, "d"), (0, 10, "a")]

# 原有区间重叠检测逻辑
overlaps = set()
for idx_a in range(len(ls)):
    for idx_b in range(len(ls)):
        if idx_a != idx_b:  
            if overlap(ls[idx_a], ls[idx_b]):
                overlaps.add(ls[idx_a])
                overlaps.add(ls[idx_b])
print(f"存在重叠的区间条目数: {len(overlaps)}")

# 新增重复字符串检测统计逻辑(无第三方依赖)
str_count = {}
str_related_intervals = {}
for item in ls:
    start, end, target_str = item
    if target_str not in str_count:
        str_count[target_str] = 0
        str_related_intervals[target_str] = []
    str_count[target_str] += 1
    str_related_intervals[target_str].append((start, end))

# 输出重复字符串统计结果
repeat_strs = {k:v for k,v in str_count.items() if v > 1}
print(f"检测到的重复字符串共{len(repeat_strs)}个:")
for s, cnt in repeat_strs.items():
    print(f"字符串`{s}`重复出现{cnt}次,关联区间为:{str_related_intervals[s]}")

运行结果说明

针对给定测试数据,运行后输出结果如下:

存在重叠的区间条目数: 3
检测到的重复字符串共1个:
字符串`a`重复出现3次,关联区间为:[(100, 350), (125, 145), (0, 10)]

如果不需要关联区间明细,只需要统计重复次数,可以直接去掉str_related_intervals相关逻辑,仅保留计数字典即可,代码会更精简。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.01 21:06:36