我目前正在研究图形遍历。find_path
,路径递增
likepath = path + [start]
返回[30, 3, 5, 8]
,而{path +=[start]
返回一个包含find_path2
所拥有的所有值的列表
已经遍历,[30, 3, 4, 0, 1, 2, 5, 8]
。在
我猜+=
的作用类似于append方法,其中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]
一个创建新列表(+),另一个修改原始列表(+=):
另外,mutable default arg也会给您带来麻烦如果您调用函数两次,则应使用None作为参数值,并在第一次调用函数时将其设置为空列表,而不是递归调用:
^{pr2}$这实际上与
+=
和list = list + [value]
之间的区别有点相同,如果每次调用函数时不创建新对象,则相同的对象/列表用于重复调用。在path = path + [start]
创建一个新列表。对列表的现有引用不会被更新,而+=
会就地修改列表。在+=
不仅仅是语法上的甜点。在相关问题 更多 >
编程相关推荐