Flatten a list of tuples in Python
I am using a recursive function to create a flow path through a maze. The function returns the correct tuples (row, col), but I need it as 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 a way to flatten this list at build time?
Similar: How to flatten a list of tuples into a pythonic list
0
source to share
2 answers
Try the following:
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.)
+6
source to share