重構列表構建程式碼
假設你有複雜的程式碼,通過從空白列表開始並重復附加到它來建立並返回列表:
def create():
result = []
# logic here...
result.append(value) # possibly in several places
# more logic...
return result # possibly in several places
values = create()
如果用列表推導替換內部邏輯是不切實際的,你可以將整個函式就地轉換為生成器,然後收集結果:
def create_gen():
# logic...
yield value
# more logic
return # not needed if at the end of the function, of course
values = list(create_gen())
如果邏輯是遞迴的,則使用 yield from
在展平結果中包含遞迴呼叫的所有值:
def preorder_traversal(node):
yield node.value
for child in node.children:
yield from preorder_traversal(child)