Python 遍历嵌套字典

标签 python dictionary nested nested-loops

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

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/

相关文章:

python - 为什么图形大小(y 轴)在此示例中波动?

python - 从 matlab 运行 python 脚本不起作用,但从终端运行正常

python - 如何在定义指示返回的非典型对象的函数期间创建提示?

python在迭代时修改dict删除

python - 如果键和值存在,则获取列表中包含的字典

javascript - 在 JavaScript 中将属性嵌套在属性数组中

python - 如何将 scrapy-splash 与旋转代理一起使用?

c# - 多值字典?

nested - 如何在 Handlebars 中使用多个助手

Javascript 正则表达式 : Find all URLs outside <a> tags - Nested Tags