用于获取供应位置的递归函数



我有一个这种格式的dictionarydestination 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']输出?

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']

列表推导返回一个列表,你的哈希条目是列表,这解释了嵌套的结果:

>>> [ 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']

最新更新