假設我有以下 Python 腳本:
def pop_and_loop():
my_list.pop(0)
my_func()
def my_func():
#do something with list item [0]
if my_list[0] finished_with:
pop_and_loop()
#continued actions if not finished with
if my_list[0] finished_with:
pop_and_loop()
my_list = [#list containing 100 items]
my_func()
這是一個合適的設定嗎?因為,我不是讓每個函式呼叫以某種方式打開,因為它必須在我離開函式的位置保持一個標記去另一個,所以理論上它在等我回來,但我從來沒有回到那個。這會產生問題嗎?您是否有不同的方式來做到這一點?
編輯:我的實際腳本比這更復雜,在處理主串列中的每個專案時,我需要呼叫許多不同的函式。本質上我的問題是我是否需要將此設定轉換為實際回圈。請記住,我將需要重繪 主串列以再次重新填充它,然后再回圈一次。那么我將如何繼續回圈呢?
我應該改為:
my_list = []
def my_func(item):
#do something with list item
if item finished_with:
return output
elif item_finished_now:
return output
while not len(my_list):
while #there are items to fill the list with:
#fill list
for x in my_list:
output = my_func(x)
#deal with output and list popping here
#sleep loop waiting for there to be things to put into the list again
time.sleep(60)
uj5u.com熱心網友回復:
你的只是遞回的一個例子。
問題和答案都是基于邊界意見的,但在大多數情況下,您更喜歡迭代解決方案(回圈)而不是遞回,除非遞回解決方案具有更簡單或更容易在代碼和推理中理解的明顯好處。
由于各種原因,Python 沒有任何遞回優化,例如尾呼叫,并為每個新級別(或函式呼叫)創建一個新的堆疊幀。這就是迭代解決方案通常會更快的原因,以及 Python 中額外遞回呼叫的開銷相當大的原因——它需要更多的堆疊記憶體并花費更多時間來創建這些幀。最重要的是,遞回深度是有限制的,大多數遞回演算法都可以很容易地轉換為迭代解決方案。
您的具體示例很簡單,可以像這樣轉換:
while my_list:
while my_list[0] != "finished":
# do stuff
my_list.pop(0)
在旁注中,請不要pop(0)使用 acollections.deque代替,因為它是O(1)代替O(N).
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/465437.html
