我有一个程序可以生成以下元组列表:
[('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/