Reputation: 141
i've been trying to strengthen my skills in lists, especially lists of lists. I have a list of people right now that I set up in a list of lists. A snippet of it is shown below. I set it up so the the list consists of [name, parent, parent].
group = [[steve,adam,avery],[avery, sarah, henry], [adam, harry, jane], [john, helene, bill], [andrew, helene, bill], [david, bill, helene]]
I want to iterate through the list of lists in order to create a new lists of lists that displays [name, parent, parent, grandparent, grandparent]. if there is no grandparent to show, then a 0 should show.
Sample output:
[[steve, adam, avery, sarah, henry, harry, jane], [avery, sarah, henry, 0, 0, 0, 0], [adam, harry, jane, 0, 0, 0, 0], [john, helene bill, 0, 0, 0, 0], [andrew, helene, bill, 0,0, 0, 0], [david, bill, helene, 0, 0, 0, 0]]
I tried interating with a for loop in range(0, len(group)) but kept receiving an error. Any help would be greatly appreciated.
Upvotes: 0
Views: 73
Reputation: 1121834
You'll have to build a mapping of name to parents first:
parents = {n: [p1, p2] for n, p1, p2 in group}
Now you can look up parents to build a new list:
[[n, p1, p2] + parents.get(p1, [0, 0]) + parents.get(p2, [0, 0])
for n, p1, p2 in group]
Demo:
>>> group = [['steve', 'adam', 'avery'], ['avery', 'sarah', 'henry'], ['adam', 'harry', 'jane'], ['john', 'helene', 'bill'], ['andrew', 'helene', 'bill'], ['david', 'bill', 'helene']]
>>> parents = {n: [p1, p2] for n, p1, p2 in group}
>>> [[n, p1, p2] + parents.get(p1, [0, 0]) + parents.get(p2, [0, 0])
... for n, p1, p2 in group]
[['steve', 'adam', 'avery', 'harry', 'jane', 'sarah', 'henry'], ['avery', 'sarah', 'henry', 0, 0, 0, 0], ['adam', 'harry', 'jane', 0, 0, 0, 0], ['john', 'helene', 'bill', 0, 0, 0, 0], ['andrew', 'helene', 'bill', 0, 0, 0, 0], ['david', 'bill', 'helene', 0, 0, 0, 0]]
Upvotes: 1