在Python中展平元组列表
我正在使用递归函数创建一个通过迷宫的流动路径。函数返回正确的路径元组(行,col),但我需要它以元组列表的形式。例如,我需要创建此表单在Python中展平元组列表,python,list,Python,List,我正在使用递归函数创建一个通过迷宫的流动路径。函数返回正确的路径元组(行,col),但我需要它以元组列表的形式。例如,我需要创建此表单 [(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
[(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)]
def FlowPathAt(fdir, row, col):
while True:
yield row, col
lItem = FlowOut(fdir, row, col)
if lItem is None: break
row, col = lItem
流出(fdir,row,col)
是一个函数,返回从(row,col)开始的下一个单元格地址
在构建过程中有没有办法将此列表展平
类似:尝试:
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
(这也总是返回一个元组列表,这似乎比有时返回一个列表,有时返回一个元组更好。如果这不可接受,您需要进行一些后处理。)这是列表增长的大量内存管理,为什么不将其重构为生成器函数:
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)]
def FlowPathAt(fdir, row, col):
while True:
yield row, col
lItem = FlowOut(fdir, row, col)
if lItem is None: break
row, col = lItem
谢谢你的意见,我将尝试这种方法。我只使用Python几周,但我真的很喜欢这种语言。此外,这个网站对于获得答案非常有帮助。感谢所有帮助他人学习的人。