【问题标题】:How to clone a queue in python?如何在python中克隆一个队列?
【发布时间】:2015-09-09 20:24:45
【问题描述】:

我有一段代码,其中有一个优先级队列,我正在尝试克隆以遍历,

import Queue as Q

import copy

    q1 = Q.PriorityQueue()

    def printQueue(q):
        while not q.empty():
            print (q.get()),
        print ''

    q1.put((5,'s'))
    q1.put((2,'e'))
    q1.put((0,'a'))
    q1.put((0,'z'))
    printQueue(copy.copy(q1)) 
    print 'second'
    printQueue(copy.copy(q1))

我在网上发现可以使用 copy.copy 进行克隆。但是在我的代码中,它不起作用。当我第二次调用 prinQueue 时,到那时优先级队列为空。有人可以指出代码有什么问题吗?

【问题讨论】:

  • 从未听说过PriorityQueues,但也许可以试试copy.deepcopy()
  • copy.deepcopy 不在 PriorityQueues 上运行。看看这个问题:stackoverflow.com/questions/3377202/…
  • 你看答案了吗?引用您提供的链接The queue module in Python is used for synchronizing shared data between threads. It is not intended as a data structure and it doesn't support copying (not even shallow copy).

标签: python


【解决方案1】:

如果你复制一个队列,它就不起作用。你得到完全相同的对象。

import Queue as Q
import copy
q1 = Q.PriorityQueue()
q2 = copy.copy(q1)
print repr(q2), repr(q1)

>> <Queue.PriorityQueue instance at 0x10568f2d8> <Queue.PriorityQueue instance at 0x10568f368>

从那里,您的 printQueue 语句实际上耗尽了 Queue。这就是为什么再次复制它是空的;您正在复制一个空队列。

如果要复制队列,可以使用Q.get()Q.put(),甚至Q.queue这样

q1 = Q.PriorityQueue()
## .. enter items

q2 = Q.PriorityQueue()
for i in q1.queue: q2.put(i)

但是,您应该阅读另一个问题,其中有几个很好的答案!特别是,您可能正在寻找一种数据结构,例如collections.deque,而不是同步的Queue,用于Threads 之间的安全通信。见how to deepcopy a queue in python

【讨论】:

    【解决方案2】:

    好吧,copy.copy 只是浅拷贝。 正如查理所说,你不能在 PriorityQueues 上进行深拷贝,但我发现由于 pq 是由队列实现的,这可能对你有用:

    q2 = Q.PriorityQueue()
    q2.queue = copy.deepcopy(q1.queue)
    printQueue(q1)
    printQueue(q2)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-04-11
      • 1970-01-01
      • 2013-03-28
      • 2023-03-30
      • 2013-01-06
      • 1970-01-01
      • 2014-05-23
      • 1970-01-01
      相关资源
      最近更新 更多