gpt4 book ai didi

Python 遍历嵌套字典

转载 作者:太空宇宙 更新时间:2023-11-04 08:13:54 26 4
gpt4 key购买 nike

首先,这里是问题和编写的代码:

def family_lineage(familytree, lineage):
'''(dict, list of strs) -> boolean
Return True if lineage specifies a list of names who are directly related
in a chain of parent-child relationships, and NOT child-parent, parent-grandchild..etc,
beginning from the first generation listed.

>>> trace_lineage({'Gina': {'Sam': {'Tina': {}},
'Li': {}},
'Guy': {}},
['Gina'])
True

>>> trace_lineage({'Gina': {'Sam': {'Tina': {}},
'Li': {}},
'Guy': {}},
['Gina', 'Sam', 'Tina'])
True
>>> trace_lineage({'Gina': {'Sam': {'Tina': {}},
'Li': {}},
'Guy': {}},
['Gina', 'Tina'])
False
'''

因此,在上面的示例中,它显示“Guy”没有 child ,而“Gina”有两个 child ,“Sam”和“Li”。 “山姆”有一个 child ,“蒂娜”。

for k, v in familytree.items():
for n, m in v.items():
if lineage[0] == any(k) and len(lineage) == 1:
return True
elif lineage[0] == k and lineage[1] == n and len(lineage) ==2:
return True
elif lineage[0] == k and lineage[1] == n and lineage[2] == m and \
len(lineage) == 3:
return True
else:
return False

所以,我的问题是,如果家谱超过三代,我该怎么写?有没有更简洁的方式来编写这段代码?

最佳答案

这是一种迭代方法,即使 lineage 不是从家谱树的顶部开始也是有效的:

def family_lineage(familytree, lineage):
trees = [familytree]
while trees:
tree = trees.pop()
trees.extend(t for t in tree.values() if t)
for name in lineage:
if name not in tree:
break
tree = tree[name]
else:
return True
return False

关于Python 遍历嵌套字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17797489/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com