using index() on multidimensional lists

前端 未结 8 2040
北恋
北恋 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:33

    For n-dimensional recursive search, you can try something like this:

    from copy import copy
    def scope(word, list, indexes = None):
        result = []
        if not indexes:
            indexes = []
        for index, item in enumerate(list):
            try:
                current_index = indexes + [index]
                result.append(current_index + [item.index(word)])
            except ValueError:
                pass
    
            if type(item[0]) == type([]):
                indexes.append(index)
                result.extend(scope(word, item, copy(indexes)))
    
        return result
    

    And the result is:

    >>> d_list = [['a', 'b', 'new', 'mpilgrim', 'new'], [['a', 'b', 'new', 'mpilgrim', 'new'], ['b', 'd', 'new', 'mpilgrim', 'new']]]
    >>> word = 'mpilgrim'
    >>> result = scope(word, d_list)
    [[0, 3], [1, 0, 3], [1, 1, 3]]
    

    Probably there are better ways to do it, but that is the one I figured out without getting any library.

    EDIT: Actually, it was not perfect and one library must be added. It's copy. Now it's ok.

提交回复
热议问题