简体   繁体   English

将元组列表转换为深层嵌套列表

[英]Converting a list of tuples to a deep nested list

I have a program that generates the following list of tuples: 我有一个程序会生成以下元组列表:

[('Government and politics', 2), ('Government', 3), ('Capital punishment', 4), ('Federal representation', 4), ('Politics', 3)]

Where the number reflects the hierarchy. 该数字反映层次结构。 I was wondering if there is a recursive way of converting this list of tuples into a nested list as follows: 我想知道是否存在将元组列表转换为嵌套列表的递归方法,如下所示:

['Government and politics', ['Government', ['Capital punishment', 'Federal representation'], 'Politics']]

It's not necessary to use recursion in this case: 在这种情况下,不必使用递归:

def nest(data, base=0):
    result = []
    for item, level in data:
        target = result
        for depth in range(base, level):
            if not (len(target) > 0 and isinstance(target[-1], list)):
                target.append([])
            target = target[-1]
        target.append(item)
    return result

The outer loop of this function iterates over the item, level pairs in your data, and the inner loop drills down to the appropriate depth, creating new sub-lists as necessary as it goes. 此函数的外部循环遍历item, level数据中的item, level对,内部循环向下钻取至适当的深度,并根据需要创建新的子列表。

The base argument is the minimum level in your data, in this case 2 . base参数是数据中的最低级别,在这种情况下为2 Here it is in action: 它在起作用:

>>> data = [
...     ('Government and politics', 2),
...     ('Government', 3),
...     ('Capital punishment', 4),
...     ('Federal representation', 4),
...     ('Politics', 3)
... ]

>>> nest(data, 2)
['Government and politics', ['Government', ['Capital punishment', 'Federal representation'], 'Politics']]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM