我一直在努力提高我的名单技能,尤其是名单清单。我现在有一个列表,我在列表列表中设置了。它的片段如下所示。我进行了设置,因此列表由[name,parent,parent]组成。
group = [[steve,adam,avery],[avery, sarah, henry], [adam, harry, jane], [john, helene, bill], [andrew, helene, bill], [david, bill, helene]]
我想遍历列表列表,以便创建一个显示[name,parent,parent,grandparent,grandparent]的列表的新列表。如果没有祖父母要显示,则应显示0。
示例输出:
[[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]]
我尝试与范围(0,len(组))中的for循环进行交互,但仍然收到错误。任何帮助将不胜感激。
答案 0 :(得分:1)
您必须首先为父母建立名称映射:
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]
演示:
>>> 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]]