gpt4 book ai didi

python - Python中list+=的含义

转载 作者:行者123 更新时间:2023-11-28 21:47:33 27 4
gpt4 key购买 nike

<分区>

我目前正在研究图形遍历。 find_path 路径递增像 path = path + [start] 返回 [30, 3, 5, 8],而 find_path2 带有路径像 path +=[start] 一样递增返回一个列表,其中包含 find_path2 具有的每个值已经遍历,[30, 3, 4, 0, 1, 2, 5, 8]

我猜 += 的行为类似于 append 方法,其中 as 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]

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com