1

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())
2
  • So you want to abstract to create kind of like a MyQueueManager that permits the creation of different queues but using the Queue API? It'd help a lot if you write how your desired API should look like to give an idea! Commented Mar 28, 2020 at 13:00
  • Does this answer your question? How do I create a variable number of variables? Commented Mar 28, 2020 at 13:01

4 Answers 4

4

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())
Sign up to request clarification or add additional context in comments.

Comments

2

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
>>>

1 Comment

You can do string.ascii_lowercase, to get the lowercase characters.
1

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())

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.