gpt4 book ai didi

python - 如何将 pythonic double for 循环转换为标准代码?

转载 作者:行者123 更新时间:2023-12-01 09:00:22 24 4
gpt4 key购买 nike

我有一段我一直难以理解的Python代码:

paths = [[end]]
while paths and paths[0][0] != start:
paths = [[parent] + path for path in paths for parent in childToParents[path[0]]]

其中 childToParents 是:

defaultdict(<class 'set'>, {'cog': {'log', 'dog'},
'dog': {'dot'},
'dot': {'hot'},
'hit': None,
'hot': {'hit'},
'log': {'lot'},
'lot': {'hot'}})

结束“cog”,开始是“hit”。路径的预期输出是:

[["hit","hot","lot","log","cog"],["hit","hot","dot","dog","cog"]]

我尝试了双 for 循环的多种变体。其中一项尝试是:

    paths=[[end]]
while paths and paths[0][0] != start:
for i in xrange(len(paths)):
for parent in childToParents[paths[i][0]]:
paths[i] = [parent] + paths[i]

但这只能给我:

[["hit","hot","dot","dog","log","cog"]]

如何将代码转换为标准双 for 循环?

最佳答案

推导式中的嵌套 for 循环从左到右工作,因此最右边的循环是循环,左边的循环是循环>。例如——

a = [1,2,3]
b = [8,9,0]

[(a1, b1) for a1 in a for b1 in b]

相当于:

l = []
for a1 in a:
for b1 in b:
l.append((a1, b1))
l

如果运行,两者都会输出以下内容

[(1, 8), (1, 9), (1, 0), (2, 8), (2, 9), (2, 0), (3, 8), (3, 9), (3, 0)]

对于您的示例代码 -

paths = [[end]]
while paths and paths[0][0] != start:
paths = [[parent] + path for path in paths for parent in childToParents[path[0]]]

相当于:

paths = [[end]]
while paths and paths[0][0] != start:
paths_, paths = paths, []
for path in paths_:
for parent in childToParents[path[0]]:
paths.append([parent] + path)
paths

请注意,paths_, paths = paths, [] 需要保留 paths 的内容进行迭代,同时仍为后续循环重置它。使用您的输入运行上述命令可以得到:

[['hit', 'hot', 'dot', 'dog', 'cog'], ['hit', 'hot', 'lot', 'log', 'cog']]

关于python - 如何将 pythonic double for 循环转换为标准代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52499465/

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