繁体   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