迭代时附加到列表 [英] Append to List while Iterating

查看:100
本文介绍了迭代时附加到列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要这种行为,但宁可有一个递减的列表,而不是一个正在增长的列表。
顺序顺序对于此操作很重要。

I need this behavior, but would rather have a diminishing list rather than a growing one. Sequence order is important for this operation.

for item in mylist:
    if is_item_mature(item):
        ## Process him
    else:
        ## Check again later
        mylist.append(item)

但我宁愿让它更像这样。这是否像我想的那样?有没有更好的方法?

but I would rather have it more like this. Does this behave like I think? Any better ways?

while mylist:
    item = list.pop(0)
    if is_item_mature(item):
        ##Process
    else:
        mylist.append(item)


推荐答案

我用你的方法看到的唯一问题是一个不断增长的清单,根据你的用法可能会耗尽你的记忆

The only problem I see with your approach is a growing list that depending upon your usage may eat up your memory

我建议您使用队列。队列的设计和灵活性足以处理结束生产和消费

I would rather suggest you to use a Queue. Queue is designed and flexible enough to handle both ended production and consumption

from Queue import Queue
q = Queue() #You can also specify the maximum size of the Queue here
# Assume your Queue was filled
while not q.empty():
    # It won;t block if there are no items to pop
    item = q.get(block = False) 
    if is_item_mature(item):
        #process
    else:
        #In case your Queue has a maxsize, consider making it non blocking
        q.put(item) 

这篇关于迭代时附加到列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆