我目前正在使用图表遍历。 find_path
路径递增
例如path = path + [start]
返回[30, 3, 5, 8]
,而find_path2
返回路径
像path +=[start]
一样递增,返回每个值find_path2
都有的列表
已遍历,[30, 3, 4, 0, 1, 2, 5, 8]
。
我猜+=
的行为与追加方法的行为一样path = path + [start]
重新分配?
有人可以解释path +=[start]
之间的区别
和path = path + [start]
def find_path2(graph, start, end, path=[]):
path += [start]
if start == end:
return path
if not start in graph:
return None
for node in graph[start]:
if node not in path:
newpath = find_path2(graph, node, end, path)
if newpath: return newpath
return None
def find_path(graph, start, end, path=[]):
path = path + [start]
if start == end:
return path
if not start 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
graph = {
0: [],
1: [],
2: [],
3: [4,2,5],
4: [0,1],
5:[8],
10:[5,6],
6:[],
30:[3]
}
print find_path(graph,30,8) #[30, 3, 5, 8]
print find_path2(graph,30,8) #[30, 3, 4, 0, 1, 2, 5, 8]
答案 0 :(得分:4)
一个创建一个新列表(+),另一个修改原始列表(+ =):
In [28]: path = [30, 3, 4, 0, 1, 2, 5, 8]
In [29]: id(path)
Out[29]: 140580805174120
In [30]: path = path + [7] # assignment = new list
In [31]: id(path)
Out[31]: 140580805174840
In [32]: path = [30, 3, 4, 0, 1, 2, 5, 8]
In [33]: id(path)
Out[33]: 140580805175416
In [34]: path += [7] # same as list.extend, modifies list
In [35]: id(path)
Out[35]: 140580805175416
如果您调用该函数两次,您的mutable default arg会导致您遇到麻烦,您应该使用None作为arg值,并在第一次调用该函数时将其设置为空列表,而不是递归调用:
def find_path2(graph, start, end, path=None):
if path is None:
path = []
这实际上与+=
和list = list + [value]
之间的差异相同,如果每次调用函数时都没有创建新对象,则相同的对象/列表用于重复调用
答案 1 :(得分:1)
path = path + [start]
创建一个新列表。不更新对列表的现有引用,而+=
就地修改列表。+=
不仅仅是语法糖。