[英]Flatten list of Tuples in Python
我正在使用遞歸函數通過迷宮創建流路。 該函數返回正確的路徑元組(行,列),但是我需要以元組列表的形式使用它。 例如,我需要創建此表單
[(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)開始的下一個單元格地址
有什么辦法可以在構建過程中扁平化此列表?
嘗試這個:
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):
while True:
yield row, col
lItem = FlowOut(fdir, row, col)
if lItem is None: break
row, col = lItem
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.