将多个不同的队列压缩到Python中的for循环中?

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了将多个不同的队列压缩到Python中的for循环中?相关的知识,希望对你有一定的参考价值。

我想在for循环或允许使用诸如索引之类的某种其他方法中压缩以下示例,而不是为每个队列对象使用不同的代码。这应该与队列类初始化(及其各自的put / get / etc。操作)结合使用,而不是直接与它们的实际内容结合使用。这可能吗?

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

如果我理解正确,您可以将队列存储在字典中:

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())
另一答案

您可以将队列对象存储在列表中:

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())
另一答案

类似的事情会起作用:

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

将打印:

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

以上是关于将多个不同的队列压缩到Python中的for循环中?的主要内容,如果未能解决你的问题,请参考以下文章

Zcat for循环中的多个压缩文件

将 for 循环中的多个打印输出值存储到列表或变量中

Python:替换多个 for 循环、多个迭代器

Matlab for循环,Python中的不同值

使用for循环(Python)追加/连接多个excel数据集

将输出重定向到for循环shell中特定目录中的多个文件