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

后端 未结 6 532
遥遥无期
遥遥无期 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:05

    You can do this by first generating a dictionary of elements at each depth (with depth as key in this dictionary and list of elements of that depth as value). The recursive function get_elements_by_depth below does this. Then all you need to do is flatten the values of that dictionary. (the function flatten_by_depth below does what you need).

    from collections import defaultdict
    
    def get_elements_by_depth(ls, cur_depth, cur_dict):
        """
            returns a dictionary with depth as key and a list of all
            elements that have that depth as value
        """
        for x in ls:
            if isinstance(x, list):
                get_elements_by_depth(x, cur_depth + 1, cur_dict)
            else:
                cur_dict[cur_depth].append(x)
        return cur_dict
    
    
    def flatten_by_depth(ls):
        """
            returns a list of lists, where the list at index i 
            contains all elements of depth i
        """
        elements_by_depth = get_elements_by_depth(ls, 0, defaultdict(list))
        max_depth = max(elements_by_depth.keys())
        # Since we're using a defaultdict, we don't have to worry about
        # missing keys in elements_by_depth
        return [
            elements_by_depth[i]
            for i in xrange(max_depth + 1)
        ]
    

    > flatten_by_depth([8, [6, 7, [-1], [4, [[10]]], 2], 1])
    [[8, 1], [6, 7, 2], [-1, 4], [], [10]]
    

提交回复
热议问题