0

我正在使用递归函数来创建穿过迷宫的流动路径。该函数返回正确的路径元组(行,列),但我需要以元组列表的形式。例如我需要创建这个表单

[(0,0),(1,1),(2,2),(3,3),(4,3)]

但是该函数返回:

[(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) 开始的下一个单元格地址

有没有办法在构建过程中展平这个列表?

类似:如何将元组列表展平为 pythonic 列表

4

2 回答 2

6

Try this:

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.)

于 2013-04-13T23:46:43.267 回答
4

列表增长需要大量内存管理,为什么不将其重构为生成器函数:

def FlowPathAt(fdir, row, col):
    while True:
        yield row, col
        lItem = FlowOut(fdir, row, col)
        if lItem is None: break
        row, col = lItem
于 2013-04-14T00:55:13.063 回答