问题描述
我正在使用递归函数来创建穿过迷宫的流路.该函数返回正确的路径元组(行,列),但是我需要以元组列表的形式使用它.例如,我需要创建此表单
I am using a recursive function to create a flow path through a maze. The function returns the correct path tuples (row,col), but I need it in the form of a List of tuples. For example I need to create this form
[(0,0),(1,1),(2,2),(3,3),(4,3)]
但是该函数返回以下内容:
However the function returns this:
[(0, 0), [(1, 1), [(2, 2), [(3, 3), (4, 3)]]]]
这是函数:
def FlowPathAt(fdir,row,col):
lItem = FlowOut(fdir,row,col)
if not lItem:
return (row,col)
else:
r,c = lItem
return [(row,col) , FlowPathAt(fdir,r,c)]
FlowOut(fdir,row,col)
是一个函数,该函数返回从(row,col)开始的下一个单元格地址.
FlowOut(fdir,row,col)
is a function that returns the next cell address starting at (row,col)
在构建过程中是否有任何方法可以使此列表扁平化?
Is there any way to flatten this list during the build?
推荐答案
尝试一下:
def FlowPathAt(fdir,row,col):
lItem = FlowOut(fdir,row,col)
if not lItem:
return [(row,col)] # More convenient base case
else:
r,c = lItem
return [(row,col)] + FlowPathAt(fdir,r,c) # Append list to list instead of nesting
(这也总是返回一个元组列表,这似乎比一个有时返回一个列表有时返回一个单一的元组更好的主意.如果这是不可接受的,则需要进行一些后处理.)
(This always returns a list of tuples, too, which just seems like a better idea than sometimes returning a list and sometimes returning a single tuple. If that's not acceptable, you'll need to do some post-processing.)
这篇关于扁平化Python中的元组列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!