在迭代时附加到列表

时间:2013-03-02 14:45:23

标签: python list iteration

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

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)

2 个答案:

答案 0 :(得分:8)

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

>>> 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循环非常适合您的需求。

答案 1 :(得分:8)

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

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

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)