How to build a nested list from a flat one in Pyth

2019-02-20 18:53发布

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条回答
干净又极端
2楼-- · 2019-02-20 19:15
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']
查看更多
登录 后发表回答