secarica
secarica

Reputation: 619

Compacting multiple distinct queues into a for loop in Python?

I would like to compact the following example in a for loop or some other method that allows to use something like an index, instead of having a distinct code for each queue object. This should be in conjunction to the queue class initialization (and their respective put/get/etc. action), not directly to their actual content. Is this possible ?

import queue

q0 = queue.Queue()
q0.put("aa")
q1 = queue.Queue()
q1.put("bb")
q2 = queue.Queue()
q2.put("cc")
# ...
qn = queue.Queue()
qn.put("xx")

print (q0.get())
print (q1.get())
print (q2.get())
# ...
print (qn.get())

Upvotes: 1

Views: 206

Answers (4)

kederrac
kederrac

Reputation: 17322

you can use a list comprehension :

n = 3 # number of queues
my_queues = [queue.Queue() for _ in range(n)] 
31
my_put = [['aa1', 'aa2'], ['bb'], ['cc']] # you can put how many elements you want

[[q.put(e) for e in l] for q, l in zip(my_queues, my_put)]

# you also can use the index to select a queue:
my_queues[1].put('bb2')

for q in my_queues:
    while not q.empty():
        print(q.get())

output:

aa1
aa2
bb
bb2
cc

Upvotes: 1

thebjorn
thebjorn

Reputation: 27311

Something like this will work:

>>> import string
>>> string.letters
'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
>>> string.letters[:24]
'abcdefghijklmnopqrstuvwx'
>>> import queue
>>> queues = [queue.Queue() for ch in string.letters[:24]]
>>> for i, ch in enumerate(string.letters[:24]):
...     queues[i].put(ch * 2)
...
>>> for q in queues:
...     print(q.get())
...

which will print:

aa
bb
cc
dd
ee
ff
gg
hh
ii
jj
kk
ll
mm
nn
oo
pp
qq
rr
ss
tt
uu
vv
ww
xx
>>>

Upvotes: 2

daveg
daveg

Reputation: 535

you can store Queue objects in a list:

import queue

data = ["aa", "bb", "cc"]
queues = []

for d in data:
    q = queue.Queue()
    q.put(d)
    queues.append(q)

for q in queues:
    print(q.get())

Upvotes: 4

Rieljun Liguid
Rieljun Liguid

Reputation: 1531

If I understood correctly, you can store the queues in a dictionary:

queues = {
    "q0": queue.Queue(),
    "q1": queue.Queue(),
}
# add new queue
queues["qn"] = queue.Queue()

queues["q0"].put("aa")
queues["q1"].put("bb")
queues["qn"].put("qq")

# You can also loop for assigning values


# Loop for getting values
for key in queues.keys():
    print(queues[key].get())

Upvotes: 1

Related Questions