如何在 Python 中随机洗牌 asyncio.Queue?

How to randomly shuffle asyncio.Queue in Python?

当我想随机打乱 Python 中的列表时,我会这样做:

from random import shuffle
shuffle(mylist)

我将如何执行与 asyncio.Queue 的实例等效的操作?我是否必须将队列转换为列表,打乱列表,然后将它们放回队列中?或者有没有办法直接做?

如您在 Queue source code 中所见,Queue 中的项目实际上存储在 _queue 属性中。可用于通过继承扩展Queue

import asyncio
from random import shuffle


class MyQueue(asyncio.Queue):
    def shuffle(self):
        shuffle(self._queue)


async def main():
    queue = MyQueue()    
    await queue.put(1)
    await queue.put(2)
    await queue.put(3)

    queue.shuffle()

    while not queue.empty():
        item = await queue.get()
        print(item)


if __name__ == '__main__':
    asyncio.run(main())

如果你想随机播放现有的 Queue 个实例,你可以直接这样做:

queue = asyncio.Queue()
shuffle(queue._queue)

由于显而易见的原因,这通常不是一个好的解决方案,但另一方面,Queue 的实现在未来以某种方式改变以使其成为问题的可能性似乎相对较低(至少对我而言) .