[英]Append to List while Iterating
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)
You can safely append items to the list, and the iteration will include those items: 您可以安全地将项目附加到列表中,迭代将包括以下项目:
>>> lst = range(5)
>>> for i in lst:
... print i
... if i < 3:
... lst.append(i + 10)
...
0
1
2
3
4
10
11
12
However, if you prefer a diminishing list, then your while
loop is perfectly suitable for your needs. 但是,如果您更喜欢缩小列表,那么您的
while
循环非常适合您的需求。
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.