简体   繁体   English

适合使用重复的function调用来循环遍历Python中的东西(即列表)吗?

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

Lets say I have the following Python script:假设我有以下 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()

Is this an appropriate setup?这是一个合适的设置吗? Because, am I not leaving each function call open in a way because its having to hold a marker at the position where I have left the function to go to another, so theoretically it is waiting for me to come back, but I'm never coming back to that one.因为,我是不是让每个 function 呼叫都以某种方式打开,因为它必须在 position 处保留一个标记,我将 function 到 go 留给另一个,所以理论上它在等我回来,但我永远不会回到那个。 Does this create problems and is there a different way you're meant to do this?这会产生问题吗?您打算采用不同的方式来做到这一点吗?

EDIT: My actual script is more complicated than this, with loads of different functions that I need to call to whilst processing each item in the main list.编辑:我的实际脚本比这更复杂,在处理主列表中的每个项目时我需要调用大量不同的函数。 Essentially my question is whether I need to convert this setup into an actual loop.本质上我的问题是我是否需要将此设置转换为实际循环。 Bearing in mind that I will need to refresh the main list to refill it again and then loop through the same again.请记住,我将需要刷新主列表以重新填充它,然后再次循环遍历它。 So how would I keep looping that?那么我将如何继续循环呢?

Should I instead have:我应该改为:

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)

Yours is simply an example of recursion.你的只是递归的一个例子。

Both the question and answer are borderline opinion-based, but in most cases you would prefer an iterative solution (loops) over recursion unless the recursive solution has a clear benefit of either being simpler or being easier to comprehend in code and in reasoning.问题和答案都是基于边界意见的,但在大多数情况下,您更喜欢迭代解决方案(循环)而不是递归,除非递归解决方案具有明显的优势,即更简单或更容易在代码和推理中理解。

For various reasons, Python does not have any recursion optimizations such as tail call and creates a new stack frame for each new level (or function call).由于各种原因,Python 没有进行尾调用等任何递归优化,而是为每个新级别(或 function 调用)创建一个新的堆栈帧 That, and more, are reasons an iterative solution would generally be faster and why the overhead of extra recursive calls in Python is rather large - it takes more memory for the stack and spends more time creating those frames.这是迭代解决方案通常更快的原因,也是 Python 中额外递归调用的开销相当大的原因 - 它需要更多 memory 用于堆栈并花费更多时间创建这些帧。 On top of all, there is a limit to the recursion depth , and most recursive algorithms can be converted to an iterative solution in an easy fashion.最重要的是,递归深度是有限制的,大多数递归算法都可以很容易地转换为迭代解决方案。

Your specific example is simple enough to convert like so:您的具体示例很简单,可以像这样进行转换:

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

On a side note, please don't pop(0) and use a collections.deque instead as it's O(1) instead of O(N) .附带一提,请不要pop(0)并使用collections.deque代替,因为它是O(1)而不是O(N)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 任何说明子列表[即某物] 是否存在于列表中的函数? - Any function which says if a sublist[i.e. something] exists inside a list or not? 哪个更快? 检查某些内容是否在Python列表中? 即会员资格与非会员资格 - Which is faster? Checking if something is in a Python list or not? I.e. membership vs non-membership 通过“ for”循环(即“ for x in list:”)访问列表时,有没有办法在同一循环中访问列表中的“ x + 1”项目? - While accessing a list through a “for” loop i.e. “for x in list:” , is there a way to access the “x+1” item in the list in the same loop? 在 Python 中获取唯一单词列表(即,不重复) - Getting a list of unique words (i.e., not duplicates) in Python 实现 for 循环:如果值发生变化,做一些事情(即 make line) - Implement for loop: if values are changing, do something (i.e. make line) 如何使用 pytorch 的 cat function 进行 K 折验证(即将 pytorch 块的列表连接在一起) - How to use pytorch's cat function for K-Fold Validation (i.e. concatenate a list of pytorch chunks together) 如何在Scrapy / Twisted中使用线程,即如何在响应回调中执行异步调用阻塞代码? - How to use threading in Scrapy/Twisted, i.e. how to do async calls to blocking code in response callbacks? 偶尔,Django消息会在请求中重复(即,它们不会被清除) - Occasionally, Django messages are repeated across requests (i.e., they are not cleared) 使用 SQLAlchemy,我可以在查询中加入 Python object(即列表)吗? - Using SQLAlchemy, can I join a Python object (i.e. a list) within a Query? Python-熊猫替换数据框列值-列数据存储为列表(即'[this,that,']) - Python - Pandas replacing dataframe column values - column data stored as list (i.e., '[this, that,'])
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM