簡體   English   中英

適合使用重復的function調用來循環遍歷Python中的東西(即列表)嗎?

[英]Appropriate to use repeated function calls to loop through something (i.e. a list) in Python?

假設我有以下 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()

這是一個合適的設置嗎? 因為,我是不是讓每個 function 呼叫都以某種方式打開,因為它必須在 position 處保留一個標記,我將 function 到 go 留給另一個,所以理論上它在等我回來,但我永遠不會回到那個。 這會產生問題嗎?您打算采用不同的方式來做到這一點嗎?

編輯:我的實際腳本比這更復雜,在處理主列表中的每個項目時我需要調用大量不同的函數。 本質上我的問題是我是否需要將此設置轉換為實際循環。 請記住,我將需要刷新主列表以重新填充它,然后再次循環遍歷它。 那么我將如何繼續循環呢?

我應該改為:

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)

你的只是遞歸的一個例子。

問題和答案都是基於邊界意見的,但在大多數情況下,您更喜歡迭代解決方案(循環)而不是遞歸,除非遞歸解決方案具有明顯的優勢,即更簡單或更容易在代碼和推理中理解。

由於各種原因,Python 沒有進行尾調用等任何遞歸優化,而是為每個新級別(或 function 調用)創建一個新的堆棧幀 這是迭代解決方案通常更快的原因,也是 Python 中額外遞歸調用的開銷相當大的原因 - 它需要更多 memory 用於堆棧並花費更多時間創建這些幀。 最重要的是,遞歸深度是有限制的,大多數遞歸算法都可以很容易地轉換為迭代解決方案。

您的具體示例很簡單,可以像這樣進行轉換:

while my_list:
    while my_list[0] != "finished":
        # do stuff
    my_list.pop(0)

附帶一提,請不要pop(0)並使用collections.deque代替,因為它是O(1)而不是O(N)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM