How to get pieces of items from a queue?

I have a queue from which I need to get pieces of 10 records and put them in a list, which is then processed further. The code below works (the “processed further” in this example just prints the list).

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]

This code is ugly. I don’t see how to improve it. I read some time ago how to use it iterwith a sentinel step , but could not figure out how my problem could use it.

Is there a better (= more elegant / pythonic) way to solve the problem?

+4
source share
1 answer

iter : iter(q.get, 'END') , , 'END' q.get().

iter(lambda: list(IT.islice(iterator, 10)), [])

10 .

import itertools as IT
import multiprocessing as mp

q = mp.Queue()
for i in range(22):
    q.put(i)
q.put("END")

iterator = iter(q.get, 'END')
for chunk in iter(lambda: list(IT.islice(iterator, 10)), []):
    print(chunk)

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
[20, 21]
+2

All Articles