Skip to main content
 首页 » 编程设计

python之在python中查找嵌套列表中元素的索引

2025年05月04日16mengfanrong

我试图在 python 中获取嵌套列表中元素的索引 - 例如 [[a, b, c], [d, e, f], [g,h]](并非所有列表的大小都相同)。 我试过使用

strand_value= [x[0] for x in np.where(min_value_of_non_empty_strands=="a")] 

但这只返回一个空列表,即使该元素存在。知道我做错了什么吗?

请您参考如下方法:

def find_in_list_of_list(mylist, char): 
    for sub_list in mylist: 
        if char in sub_list: 
            return (mylist.index(sub_list), sub_list.index(char)) 
    raise ValueError("'{char}' is not in list".format(char = char)) 
 
example_list = [['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h']] 
 
find_in_list_of_list(example_list, 'b') 
(0, 1)