简体   繁体   中英

How to clone a queue in python?

I have got a piece of code where I have a priority queue and I am trying to clone to traverse,

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

I found on the web that I can do clone using copy.copy. However in my code, it is not working. When I call prinQueue for the second time, by that time the priority queue is empty. Could somebody point out what is wrong with the code?

If you copy a queue, it doesn't work. You get back exactly the same object.

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>

From there, your printQueue statement actually depletes the Queue . That's why it's empty if you copy it again; you're copying an empty queue.

If you want to copy the queue, you can use Q.get() and Q.put() , or even Q.queue like so

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

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

But, you should read the other question, which has a couple of good answers! In particular, you may be looking for a data structure, that's collections.deque for example, not the synchronized Queue , intended for safe communication between Threads . See how to deepcopy a queue in python .

Well, copy.copy just shallow copy. As Charlie says, you can't do deep copy on PriorityQueues, but I found that since pq implemented by a queue, this might work for you:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM