iteritems只给一把钥匙

时间:2016-06-17 18:15:53

标签: python loops

所以我有这个功能:

cached_list = []
def build_dependency_list(list, tree, cache=True):
    global cached_list
    if not tree:
        return
    if cache:
        cached_list = list
    pp = pprint.PrettyPrinter(indent=4)
    pprint.pprint(tree)
    for key, value in tree.iteritems():
        pprint.pprint(key)
        if key not in list:
            list.append(key)
        return build_dependency_list(list, value, cache)

但是当我尝试用一​​些词典运行它时,我得到了这个

{'drawee': {'fbcore': {}, 'support-v4': {}},
 'fbcore': {},
 'imagepipeline': {'bolts-tasks': {'junit': {'hamcrest-core': {}}},
                   'fbcore': {},
                   'imagepipeline-base': {'bolts-tasks': {'junit': {'hamcrest-core': {}}},
                                          'fbcore': {},
                                          'library': {},
                                          'support-v4': {}},
                   'library': {},
                   'support-v4': {}}}
'fbcore'

知道为什么fbcode是唯一被迭代的人?

1 个答案:

答案 0 :(得分:2)

在第一次迭代期间从函数返回

for key, value in tree.iteritems():
    pprint.pprint(key)
    if key not in list:
        list.append(key)
    return build_dependency_list(list, value, cache)
    # ^^ part of the loop

因此只生成第一个键值对,然后递归,当递归调用完成时,循环结束