【发布时间】:2015-10-02 07:15:15
【问题描述】:
我有一个queue,我需要从中获取 10 个条目的块并将它们放入一个列表中,然后对其进行进一步处理。下面的代码有效(在示例中,“进一步处理”只是将列表打印出来)。
import multiprocessing
# this is an example of the actual queue
q = multiprocessing.Queue()
for i in range(22):
q.put(i)
q.put("END")
counter = 0
mylist = list()
while True:
v = q.get()
if v == "END":
# outputs the incomplete (< 10 elements) list
print(mylist)
break
else:
mylist.append(v)
counter += 1
if counter % 10 == 0:
print(mylist)
# empty the list
mylist = list()
# this outputs
# [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
# [10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
# [20, 21]
这段代码很难看。我不知道如何改进它 - 我前段时间阅读了how to use iter with a sentinel,但没有看到我的问题如何利用它。
有没有更好(= 更优雅/pythonic)的方法来解决这个问题?
【问题讨论】: