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

如何检查普通列表中的字符串是否存在于嵌套列表并返回其索引?

Find Indices of List1 Elements in Nested List2

Problem Overview

We have two lists to work with:

  • A flat list list1 holding individual strings
  • A nested list list2 where each entry is a sublist of strings

The goal is to check every string in list1 to see if it exists anywhere in list2. For any matches, we need to return the pair of indices (outer_index, inner_index):

  • outer_index: The position of the sublist within list2
  • inner_index: The position of the matching string inside that sublist

Example Inputs

list1 = ['john','amal','joel','george']
list2 = [['john'],['jack','john','mary'],['howard','john'],['jude']]

Solution Approach

We can use nested iteration (with the help of enumerate() to track indices) to efficiently scan through both lists. To organize results for all elements in list1, a dictionary works well—it lets us map each element to its list of matching index pairs.

Complete Solution Code

list1 = ['john','amal','joel','george']
list2 = [['john'],['jack','john','mary'],['howard','john'],['jude']]

# Initialize a dictionary to store results for each element in list1
element_indices = {elem: [] for elem in list1}

# Iterate through each sublist and its index in list2
for outer_idx, sublist in enumerate(list2):
    # Iterate through each item and its index in the current sublist
    for inner_idx, item in enumerate(sublist):
        # If the item is in list1, add its indices to the dictionary
        if item in element_indices:
            element_indices[item].append((outer_idx, inner_idx))

print(element_indices)

Output Breakdown

Running this code will produce:

{
 'john': [(0, 0), (1, 1), (2, 1)],
 'amal': [],
 'joel': [],
 'george': []
}

This tells us:

  • 'john' appears three times in list2 at positions (0,0), (1,1), and (2,1)
  • 'amal', 'joel', and 'george' don't appear anywhere in list2

Single Element Check (As In Your Demo)

If you only need to check one specific element (like 'john'), you can use the list comprehension you provided—with a small tweak for exact matches:

out = [(ind, ind2) for ind, i in enumerate(list2) for ind2, y in enumerate(i) if y == 'john']
print(out)  # Output: [(0, 0), (1, 1), (2, 1)]

Note: I changed 'john' in y to y == 'john' because y is a string—in would check for substrings, while == ensures we get exact matches. If you intended substring searches, you can revert to 'john' in y.

Key Details

  • enumerate() is essential here—it lets us grab both the index and the element as we loop through lists
  • Using a dictionary keeps results organized and easy to reference later
  • The solution handles multiple occurrences of the same element by appending all matching index pairs

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 08:43:47