繁体   English   中英

在迭代时附加到列表

[英]Append to List while Iterating

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

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

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

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

您可以安全地将项目附加到列表中,迭代将包括以下项目:

>>> lst = range(5)
>>> for i in lst:
...     print i
...     if i < 3:
...         lst.append(i + 10)
... 
0
1
2
3
4
10
11
12

但是,如果您更喜欢缩小列表,那么您的while循环非常适合您的需求。

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

我宁愿建议你使用队列 队列设计灵活,足以处理生产和消费

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) 

暂无
暂无

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM