为什么None被附加在列表中

时间:2015-06-25 11:10:56

标签: python list dictionary

在下面的代码中,我想要来自dict的叶元素。

group_children_map={'Mould': ['Yeast'], 'Living Organism': ['Animal', 'Plant', 'Mould'], 'Animal': ['Lion', 'Tiger', 'Cat', 'DOG'], 'Plant': ['Tulsi', 'Hibiscus', 'Aloe Vera']}
print group_children_map
node='Living Organism'
leaf_list=[]
def find_leaf(node):
    try_leaf=group_children_map.get(node)
    if try_leaf is None:
        #print node
        return node
    else:
        print try_leaf,"list"
        for l in try_leaf:
            #print l
            leaf_list.append(find_leaf(l))

find_leaf(node)

print leaf_list

预期输出:

['Lion', 'Tiger', 'Cat', 'DOG', 'Tulsi', 'Hibiscus', 'Aloe Vera', 'Yeast']

实际结果:

 ['Lion', 'Tiger', 'Cat', 'DOG', None, 'Tulsi', 'Hibiscus', 'Aloe Vera', None, 'Yeast', None]

为什么没有附加在列表中...需要帮助:/

2 个答案:

答案 0 :(得分:4)

您的find_leaf()函数并不总是显式返回某些内容。当函数刚刚结束None时返回。

如果try_leaf is None为真,该函数将只返回一些内容。如果错误,您递归调用find_leaf(),但在递归调用之后,您不会明确地返回任何内容。

您可以明确测试该案例:

for l in try_leaf:
    leaf = find_leaf(l)
    if leaf is not None:
        leaf_list.append(leaf)

或者将leaf_list附加到代码的另一个分支,而不是返回:

def find_leaf(node):
    if node not in group_children:
        leaf_list.append(node)
    else:
        for l in group_children[node]:
            find_leaf(l)

答案 1 :(得分:0)

@Martin Pieters已经提供了你的答案只是一个小插件如果你想使用该方法而不添加任何

<强>码

group_children_map={'Mould': ['Yeast'], 'Living Organism': ['Animal', 'Plant', 'Mould'], 'Animal': ['Lion', 'Tiger', 'Cat', 'DOG'], 'Plant': ['Tulsi', 'Hibiscus', 'Aloe Vera']}
print group_children_map
node='Living Organism'
leaf_list=[]
def find_leaf(node):
    try_leaf=group_children_map.get(node)
    if try_leaf is None:
        return node
    else:
        print try_leaf,"list"
        for l in try_leaf:
            print l,
            leaf_list.extend(group_children_map[l]) #added the list where the dictionary keys matches

find_leaf(node)

print leaf_list