【问题标题】:Flatten list of Tuples in PythonPython中元组的扁平化列表
【发布时间】:2013-04-06 07:47:20
【问题描述】:

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

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

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

类似:How to flatten a list of tuples into a pythonic list

【问题讨论】:

    标签: python list


    【解决方案1】:

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

    def FlowPathAt(fdir, row, col):
        while True:
            yield row, col
            lItem = FlowOut(fdir, row, col)
            if lItem is None: break
            row, col = lItem
    

    【讨论】:

    • 感谢您的输入,我会尝试这种方法。只使用 Python 几个星期,但我真的很喜欢这种语言。此外,这个网站对于获得答案非常有帮助。感谢所有帮助他人学习的人。
    【解决方案2】:

    试试这个:

    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
    

    (这也总是返回一个元组列表,这似乎比有时返回一个列表有时返回一个元组更好。如果这不可接受,你需要做一些后处理。)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-02-27
      • 2016-01-14
      • 2020-12-04
      • 1970-01-01
      • 1970-01-01
      • 2010-12-08
      • 1970-01-01
      相关资源
      最近更新 更多