简体   繁体   中英

Flatten list of Tuples in 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)]]]]

Here is the function:

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) is a function that returns the next cell address starting at (row,col)

Is there any way to flatten this list during the build?

Similar: How to flatten a list of tuples into a pythonic list

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

That's alot of memory management for list growth, why not refactor it into a generator function:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM