Python 获取供应位置的递归函数
我有一本Python 获取供应位置的递归函数,python,Python,我有一本字典,格式为目的地位置:供应位置列表- 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]
字典
,格式为目的地位置:供应位置列表
-
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(“源代码是”,get_source('A'))
时,我得到源代码是[['D'],['Z']]]
。它是列表中的一个列表。为什么我以这种方式获得输出?如何以的形式获得输出源是['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']
@Karvy1您应该使用