5

Worker:

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

Putting items into queue:

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

Output:

>>> A banana is yellow

How would I be able to achieve this? I tried it and got ValueError: too many values to unpack, only then I realized that my q.put() put both of the variables into the queue.

Is there any way to put a "set" of variables/objects into one single queue item, like I tried to do?

4

4 に答える 4

11

Yes, use a tuple:

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

It should be automatically unpacked (should, because I can't try it atm).

于 2012-10-19T15:16:52.433 に答える
1

I just would make a list:

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

and then get it like that:

result = q.get()
fruit = result[0]
colour = result[1]
于 2020-05-01T13:45:21.950 に答える
0

So, I think the best way to go about this is to refactor your data a bit. Make some sort of object to hold a pair of values (in this case fruit and colour), and then put that object into the queue, then pull out the variables when needed.

I can post some sample code later if you would like.

于 2012-10-19T15:19:31.633 に答える
0

Python also provides data abstraction with the help of classes.

So, another approach can be to put an object (abstracting the related info together) with the help of a class as shown below.

class Fruit(object):
   def __init__(self, name, color):
       self.name = name
       self.color = color

q.put(Fruit('banana', 'yellow'))

def worker():
    while True:
        fruit  = q.get()
        print 'A ' + fruit.name + ' is ' + fruit.color
        q.task_done()
于 2020-12-18T20:21:03.370 に答える