如何在Python中从一个平面列表构建一个嵌套列表? [英] How to build a nested list from a flat one in Python?
本文介绍了如何在Python中从一个平面列表构建一个嵌套列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个简单的清单,例如:
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']
任何提示如何在Python中做到这一点?
Any tips how to do that in Python?
推荐答案
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
示例:
>>> list(nested(flat, 0))
['1', ['1-1', ['1-1-1'], '1-2'], '2', ['2-1', '2-2'], '3']
这篇关于如何在Python中从一个平面列表构建一个嵌套列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文