Finding the index of an element in nested lists in python

前端 未结 4 493
醉梦人生
醉梦人生 2020-12-10 09:25

I am trying to get the index of an element in nested lists in python - for example [[a, b, c], [d, e, f], [g,h]] (not all lists are the same size). I have tried

4条回答
  •  一生所求
    2020-12-10 10:21

    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)
    

提交回复
热议问题