递归功能以获取供应位置

时间:2018-09-26 07:01:36

标签: python

我有一个dictionary,格式为destination location : list of supply locations-

dict_input = {'A':['B'], 'B':['C','Y'], 'C':['D'], 'Y':['Z']}

对于目的地位置'A',我想找出供应链中的最终供应位置(在这种情况下为位置'D''Z'

我已经编写了这样的函数-

def get_source(node):
    source = []
    if node in dict_input:
        next_node = dict_input[node]
                 source = [get_source(i) for i in next_node]
        return list(source)
    else:
        return node

执行函数print("The source is", get_source('A'))时,我得到The source is [[['D'], ['Z']]]。它是列表中的列表。为什么我以这种方式获得输出?如何以The source is ['D', 'Z']的形式获取输出?

2 个答案:

答案 0 :(得分:1)

dict_input = {'A':['B'], 'B':['C','Y'], 'C':['D'], 'Y':['Z']}

def get_source(node):
    source = []
    if node in dict_input:
        next_node = dict_input[node]
        for i in next_node:
            source += get_source(i) # source.extend(get_source(i))

        return source
    else:
        return [node,] # just return node if output of get_source('Z') should be just 'Z' 


print(get_source('A')) #['D', 'Z']
print(get_source('B')) #['D', 'Z']
print(get_source('Z')) #['Z']

答案 1 :(得分:0)

列表理解会返回一个列表,您的哈希条目是列表,它解释了嵌套结果:

>>> [ get_source(i) for i in dict_input['A'] ]
[[['D'], ['Z']]]

您可以使用列表来累积结果,并使用列表组合仅访问所有节点:

def get_source(n, acc=[]):
    if n in dict_input:
        [ get_source(i, acc) for i in dict_input[n] ]
    else:
        acc.append(n)
    return acc

>>> get_source('A', [])
['D','Z']