How to build a nested list from a flat one in Python?

后端 未结 1 620
没有蜡笔的小新
没有蜡笔的小新 2021-01-17 02:26

I have a flat list, for example:

flat = [\'1\', \'1-1\', \'1-1-1\', \'1-2\', \'2\', \'2-1\', \'2-2\', \'3\']

that I need to convert to a ne

相关标签:
1条回答
  • 2021-01-17 02:45
    def nested(flat, level=0):
        for k, it in itertools.groupby(flat, lambda x: x.split("-")[level]):
            yield next(it)
            remainder = list(nested(it, level + 1))
            if remainder:
                yield remainder
    

    Example:

    >>> list(nested(flat, 0))
    ['1', ['1-1', ['1-1-1'], '1-2'], '2', ['2-1', '2-2'], '3']
    
    0 讨论(0)
提交回复
热议问题