Python - How to sort multidimensional list to two-dimensional list?

后端 未结 6 494
遥遥无期
遥遥无期 2021-01-18 18:39

How i can sort multidimensional list to two-dimensional list?

Multidimensional input: [8, [6, 7, [-1], [4, [[10]]], 2], 1]

Desired two-dimension

6条回答
  •  说谎
    说谎 (楼主)
    2021-01-18 19:06

    Somebody recently posted a similar question which, by the time I composed my answer, was closed as a duplicate. So I figured I'd add my answer here.

    def extract_entries(nested_list, new_list=[]):
        # Add the list of all of the items in  that are NOT lists themselves. 
        new_list.append( [ e for e in nested_list if type(e) != list ] )
    
        # Look at entries in  that ARE lists themselves.
        for entry in nested_list:
            if type(entry) == list:
                extract_entries(entry, new_list)
    
        return new_list
    

    Testing:

    M = [8, [6, 7, [-1], [4, [[10]]], 2], 1]
    print(extract_entries(M))
    # Returns: [[8, 1], [6, 7, 2], [-1], [4], [], [10]]
    

提交回复
热议问题