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

高效检查字符串列表是否存在于嵌套列表中并获取索引的方法

高效解决嵌套列表元素索引匹配问题

核心思路:预构建元素-索引映射字典

要实现最快的查询效率,最优方案是先把嵌套列表中的所有元素与其所在子列表的索引建立映射(用字典存储),之后直接通过字典查询目标元素的索引,避免重复遍历嵌套列表。

具体实现步骤

  1. 构建映射字典
    遍历嵌套列表的每个子列表及其索引,将每个元素作为字典的键,对应的子列表索引作为值。如果同一元素出现在多个子列表中,字典会保留该元素最后一次出现的子列表索引(若需要保留所有索引,可将值改为列表类型存储)。

  2. 生成结果列表
    遍历目标字符串列表,对每个元素检查是否存在于映射字典中,存在则生成(元素, 索引)的元组,最终收集所有符合条件的元组。

代码示例

lists = [["apple","car"],["street","beer"],["plate"]]
Test = ["apple","plate"]
Test2 = ["car","street"]
Test3 = ["pineapple"]

# 构建元素到子列表索引的映射字典
element_index_map = {}
for sub_idx, sublist in enumerate(lists):
    for item in sublist:
        element_index_map[item] = sub_idx

# 处理Test列表
result1 = [(item, element_index_map[item]) for item in Test if item in element_index_map]
print(result1)  # 输出: [('apple', 0), ('plate', 2)]

# 处理Test2列表
result2 = [(item, element_index_map[item]) for item in Test2 if item in element_index_map]
print(result2)  # 输出: [('car', 0), ('street', 1)]

# 处理Test3列表
result3 = [(item, element_index_map[item]) for item in Test3 if item in element_index_map]
print(result3)  # 输出: []

效率说明

  • 构建字典的时间复杂度为O(T),其中T是嵌套列表中所有元素的总数量。
  • 查询目标列表的时间复杂度为O(N),其中N是目标列表的长度。
  • 这种方法比每次查询都遍历嵌套列表(时间复杂度O(M*N),M是子列表数量)高效得多,尤其适合嵌套列表规模大或需要多次查询的场景。

扩展:处理元素多索引场景

如果同一元素出现在多个子列表中,需要保留所有对应的索引,可以修改映射字典的构建逻辑:

element_index_map = {}
for sub_idx, sublist in enumerate(lists):
    for item in sublist:
        if item not in element_index_map:
            element_index_map[item] = []
        element_index_map[item].append(sub_idx)

# 此时查询会返回该元素的所有索引,比如若lists中有两个apple,结果会是[('apple', [0, 1])]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 11:31:01