【发布时间】:2019-03-12 13:54:37
【问题描述】:
在下面的函数中,当我使用path = path + [start] 时,我会得到['A', 'B', 'E'] 的结果,但是当我使用path += [start] 时,我会得到['A', 'B', 'D', 'E'] 的结果。为什么?
我的代码:
graph1 = {'A':['B','C'],
'B':['A','D','E'],
'C':['A','F'],
'D':['B'],
'E':['B','F'],
'F':['C','E']}
def find_path(graph,start,end,path=[]):
path = path + [start]
if start == end:
return path
if start not in graph:
return None
for node in graph[start]:
if node not in path:
newpath = find_path(graph,node,end,path)
if newpath:
return newpath
return None
print(find_path(graph1,'A','E'))
【问题讨论】:
-
paht + [start]创建一个新列表,而+= [start]没有。请参阅 “Least Astonishment” and the Mutable Default Argument 了解为什么这会影响您的结果。 -
好的,谢谢,我去看看^^
标签: python