You need to enable JavaScript to run this app. Python 字符串列表大小写不敏感重复项分组及索引提取
优惠活动
大模型
产品
解决方案
定价
更多

Python 字符串列表大小写不敏感重复项分组及索引提取

实现逻辑

  • 大组划分:将所有仅存在大小写差异的伪重复项归入同一个大组,匹配时将字符串统一转小写(或大写)作为匹配键,消除大小写带来的差异
  • 小组划分:在每个大组范围内,将完全相同的字面重复项的索引归集为同一列表,匹配时保留字符串原始大小写,不做大小写转换
  • 结构输出:按大组嵌套内部小组的结构整理,最终形成要求的三层嵌套索引列表

可复用函数实现

def get_nested_dupe_index(str_list):
    group_storage = {}
    for idx, content in enumerate(str_list):
        # 大组匹配键:消除大小写差异
        group_key = content.lower()
        # 初始化大组的内部字面存储
        if group_key not in group_storage:
            group_storage[group_key] = {}
        # 按原始字面存入对应索引列表
        if content not in group_storage[group_key]:
            group_storage[group_key][content] = []
        group_storage[group_key][content].append(idx)
    # 整理为目标三层结构
    result = [list(literal_group.values()) for literal_group in group_storage.values()]
    return result

# 测试用例
a = ['bar','bar','foo','Bar','Foo','Foo']
print(get_nested_dupe_index(a))

输出验证

运行测试用例得到的结果和题目要求完全一致:[[[0, 1], [3]], [[2], [4, 5]]]

  • 第一组大项对应不区分大小写的"bar"类,内部两个小组分别归集了全小写bar的索引[0,1]、首字母大写Bar的索引[3]
  • 第二组大项对应不区分大小写的"foo"类,内部两个小组分别归集了全小写foo的索引[2]、首字母大写Foo的索引[4,5]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.10 13:15:05