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

标签 python list python-3.x tuples nested-lists

我有一个程序可以生成以下元组列表:

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

其中数字反射(reflect)了层次结构。我想知道是否有一种递归方法可以将此元组列表转换为嵌套列表,如下所示:

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

最佳答案

在这种情况下没有必要使用递归:

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

此函数的外部循环迭代数据中的item, level 对,内部循环向下钻取到适当的深度,根据需要创建新的子列表。

base 参数是数据中的最低级别,在本例中为 2。这是实际操作:

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

关于python - 将元组列表转换为深层嵌套列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41406013/

相关文章:

python - 需要一个金发姑娘正则表达式模式 - 不要太贪婪也不要太自私

python - 当掩码为一个时,numpy 更改数组值

python - 是否有可以在 Python 集上使用的计数类型的方法?

java - List<String> 到 ArrayList<String> 的转换问题

python多处理/线程代码提前退出

java - 使用 pem 证书打开 SSL 套接字

python - Pandas pd.isnull() 函数

python - 从列表中删除项目会导致列表变为 NoneType

python - 对未知秩的张量应用函数(平均倒数秩)

python-3.x - Ubuntu 18.04 LTS 上的 Hyperledger Sawtooth 安装问题