using index() on multidimensional lists

前端 未结 8 2074
北恋
北恋 2020-12-10 03:00

For a one dimensional list, the index of an item is found as follows:

 a_list = [\'a\', \'b\', \'new\', \'mpilgrim\', \'new\']
 a_list.index(\'mpilgrim\')
         


        
8条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-10 03:50

    You can use the following sample method too:

    data = [[1, 1,2],[12,4],[6]]
    
    def m_array_index(arr, searchItem):
        for i,x in enumerate(a):
            for j,y in enumerate(x):
                if y == searchItem:
                    return i,j
        return -1,-1#not found
    
    print m_array_index(data, 6)
    

    Or with all occurrences(sure code could be optimized - modified to work with generators and so on - but here is just a sample):

    occurrences = lambda arr, val: tuple((i,j) for i,x in enumerate(arr) for j,y in enumerate(x) if y == val) or ((-1,-1))
    
    print occurrences(data, 1) # ((0, 0), (0, 1))
    print occurrences(data, 12) # ((1, 0),)
    print occurrences(data, 11) # (-1, -1)
    

提交回复
热议问题