How can I put and get a set of multiple items in a queue?

Working:

def worker(): while True: fruit, colour = q.get() print 'A ' + fruit + ' is ' + colour q.task_done() 

Entering elements into the queue:

 fruit = 'banana' colour = 'yellow' q.put(fruit, colour) 

Output:

 >>> A banana is yellow 

How can I achieve this? I tried and got ValueError: too many values to unpack , only then did I realize that my q.put() put both variables in the queue.

Is there a way to put a β€œset” of variables / objects in one element of the queue as I tried?

+4
source share
2 answers

Yes, use a tuple:

 fruit = 'banana' colour = 'yellow' q.put((fruit, colour)) 

It should be automatically unpacked (should, because I cannot try its atm).

+7
source

So, I think the best way to do this is to reorganize your data a bit. Make some kind of object to hold a pair of values ​​(in this case, the fruit and color), and then put this object in the queue, then pull out the variables when necessary.

I can send some sample code later if you want.

0
source

Source: https://habr.com/ru/post/1440815/


All Articles