我有一个生成以下元组列表的程序:
[('Government and politics', 2), ('Government', 3), ('Capital punishment', 4), ('Federal representation', 4), ('Politics', 3)]
数字反映了层次结构。我想知道是否有一种递归方式将这个元组列表转换为嵌套列表,如下所示:
['Government and politics', ['Government', ['Capital punishment', 'Federal representation'], 'Politics']]
答案 0 :(得分:2)
在这种情况下没有必要使用递归:
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']]