How to get chunks of elements from a queue?

2024/11/17 12:49:50

I have a queue from which I need to get chunks of 10 entries and put them in a list, which is then processed further. The code below works (the "processed further" is, in the example, just print the list out).

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) listprint(mylist)breakelse:mylist.append(v)counter += 1if counter % 10 == 0:print(mylist)# empty the listmylist = 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 do not see how to improve it - I read some time ago how to use iter with a sentinel but fail to see how my problem could make use of it.

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

Answer

You could use iter twice: iter(q.get, 'END') returns an iterator which can iterate over the values in the queue until 'END' is returned by q.get().

Then you could use the grouper recipe

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

to group the iterator into chunks of 10 items.

import itertools as IT
import multiprocessing as mpq = 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)

yields

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
[20, 21]
https://en.xdnf.cn/q/71553.html

Related Q&A

Receiving commandline input while listening for connections in Python

I am trying to write a program that has clients connect to it while the server is still able to send commands to all of the clients. I am using the "Twisted" solution. How can I go about this…

Passing a parameter through AJAX URL with Django

Below is my code. n logs correctly in the console, and everything works perfectly if I manually enter the value for n into url: {% url "delete_photo" iddy=2%}. Alas, when I try to use n as a …

WARNING: toctree contains reference to nonexisting document error with Sphinx

I used the sphinx-quickstart to set everything up. I used doc/ for the documentation root location. The folder containing my package is setup as: myfolder/doc/mypackage/__init__.pymoprob.py...After the…

Removing nan from list - Python

I am trying to remove nan from a list, but it is refusing to go. I have tried both np.nan and nan.This is my code:ztt = [] for i in z:if i != nan:ztt.append(i) zttor:ztt = [] for i in z:if i != np.nan…

Safely unpacking results of str.split [duplicate]

This question already has answers here:How do I reliably split a string in Python, when it may not contain the pattern, or all n elements?(5 answers)Closed 6 years ago.Ive often been frustrated by the…

Get a structure of HTML code

Im using BeautifulSoup4 and Im curious whether is there a function which returns a structure (ordered tags) of the HTML code. Here is an example:<html> <body> <h1>Simple example</h…

max_help_position is not works in python argparse library

Hi colleagues I have the code (max_help_position is 2000):formatter_class=lambda prog: argparse.HelpFormatter(prog, max_help_position=2000) parser = argparse.ArgumentParser(formatter_class=formatter_cl…

Python - How to parse argv on the command line using stdin/stdout?

Im new to programming. I looked at tutorials for this, but Im just getting more confused. But what Im trying to do is use stdin and stdout to take in data, pass it through arguments and print out outpu…

Bad Request from Yelp API

Inspired by this Yelp tutorial, I created a script to search for all gyms in a given city. I tweaked the script with these updates in order to return ALL gyms, not just the first 20. You can find the g…

Python: test empty set intersection without creation of new set

I often find myself wanting to test the intersection of two sets without using the result of the intersections.set1 = set([1,2]) set2 = set([2,3]) if(set1 & set2):print("Non-empty intersection…