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

一笑奈何 提交于 2019-12-19 12:22:48

问题


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 nested list, where each level (dash followed by a number) starts a new sublist, for example:

result = ['1', ['1-1', ['1-1-1'], '1-2'], '2', ['2-1', '2-2'], '3']

Any tips how to do that in Python?


回答1:


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']


来源:https://stackoverflow.com/questions/8916209/how-to-build-a-nested-list-from-a-flat-one-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!