为什么“无”会附加在lis中

2024-06-07 15:26:39 发布

您现在位置:Python中文网/ 问答频道 /正文

在下面的代码中,我需要dict中的leaf元素

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]

为什么没有人被添加到列表中…需要帮助:/


Tags: nonenodemapgrouplistcatprinttry
2条回答

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

只有当try_leaf is None为true时,函数才会返回某些内容。如果为false,则递归调用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)

@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

相关问题 更多 >

    热门问题