扁平化Python中的元组列表 [英] Flatten list of Tuples in Python

查看:128
本文介绍了扁平化Python中的元组列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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?

类似:如何拼合列表元组变成一个pythonic列表

推荐答案

尝试一下:

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中的元组列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆