Reputation: 11
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']]
Upvotes: 1
Views: 96
Reputation: 59178
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.
The base
argument is the minimum level in your data, in this case 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']]
Upvotes: 2