【发布时间】:2017-07-20 01:39:07
【问题描述】:
所以 x 是我在嵌套列表 t 中寻找的值。我理解整个代码和列表理解发生了什么,我不明白的是 [5] 在什么时候变成路径,然后 [3,5] 变成路径,最后 [1,3,5] 被返回以显示价值的最终路径。
def findPath(t, x):
if t[0] == x:
return [t[0]]
for path in [findPath(branch, x) for branch in t[1:]]:
if path:
return [t[0]] + path
t = [1, [3, [4], [5]], [2]]
findPath(t, 5)
#returns [1,3,5]
findPath(t, 2)
#returns [1 ,2]
这是一个帮助我逐步理解的链接,我只是不明白列表如何成为最终返回 [t[0]] + 路径的路径。 https://goo.gl/ZRrZv7
【问题讨论】:
标签: python list recursion list-comprehension nested-lists