假设我有以下 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)
你的只是递归的一个例子。
问题和答案都是基于边界意见的,但在大多数情况下,您更喜欢迭代解决方案(循环)而不是递归,除非递归解决方案具有更简单或更容易在代码和推理中理解的明显好处。
由于各种原因,Python 没有任何递归优化,例如尾调用,并为每个新级别(或函数调用)创建一个新的堆栈帧。这就是迭代解决方案通常会更快的原因,以及 Python 中额外递归调用的开销相当大的原因——它需要更多的堆栈内存并花费更多时间来创建这些帧。最重要的是,递归深度是有限制的,大多数递归算法都可以很容易地转换为迭代解决方案。
您的具体示例很简单,可以像这样转换:
while my_list:
while my_list[0] != "finished":
# do stuff
my_list.pop(0)
在旁注中,请不要pop(0)
使用 acollections.deque
代替,因为它是O(1)
代替O(N)
.
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句