如何在python中深度拷貝隊列? 謝謝如何在python中深度拷貝隊列
2
A
回答
0
不知道你確切的需求,但它可能是你會對我在DaniWeb關於優先級隊列的討論中發佈的代碼感興趣。該列表是容易通過切片等
#Python 2.6.5
from random import randint
class Priority:
def __init__(self,prioritylevels=5):
"""The constructor builds list for priority queue which would be used later
"""
self.prioritylevels = prioritylevels
self.pq = [[] for priority in range(self.prioritylevels)] # prioritylevels
def add_to_queue(self, data, priority=None):
"""Add every received in data and use priority parameter or
its priority key to get its priority value (1 == highest) in the global queue
"""
if priority is None: priority = data['priority']-1
else: priority -= 1
if 0 <= priority < self.prioritylevels:
self.pq[priority].append(data)
else: raise ValueError,"Priority level out of bounds: %s" % priority
def get(self):
""" get lowest priority values first from queue """
for priorityevents in self.pq:
while priorityevents:
yield priorityevents.pop(0) ## use list as queue to keep insertion order (remove from front)
def num_items(self):
return sum(len(q) for q in self.pq)
if __name__ == '__main__':
myqueue = Priority(8)
for i in range(100000):
item=randint(0,234234)
if not i % 10000: print i,
priority=(item & 0b111) +1 ## lets three lowest bits decide which priority we give
myqueue.add_to_queue(('Number',item),priority=priority)
print "\n%i items in queues" % myqueue.num_items()
print "Items by priorities"
print '\n'.join("%i: %i" % (priority+1,len(q)) for priority, q in enumerate(myqueue.pq))
print "\nGetting items out of queue in priority order:"
priority=0
for description,i in myqueue.get():
assert (i & 0b111 >= priority), '** Bug ***' ## validity test priority must be same or lower for items
priority = i & 0b111
# empty after get
print "Finished"
print "%i items in queue" % myqueue.num_items()
10
在Python的queue
module用於線程之間的同步共享數據保存拷貝。這是而不是打算作爲數據結構,它不支持複製(甚至不是淺拷貝)。
(有可能通過.get
和.put
構建一個隊列的許多deepcopy的公司,但原有隊列將被銷燬。)
如果你想有一個隊列(或堆棧)的數據結構,use a collections.deque
。如果您想要優先隊列,請使用heapq
module。該雙層支持deepcopy。 heapq由列表支持,因此deepcopy也受支持。
相關問題
- 1. 深拷貝在Python
- 2. 深拷貝在Python
- 3. python中的深拷貝
- 4. 淺拷貝或深拷貝?
- 5. 如何深度拷貝函數對象
- 6. 淺拷貝和深拷貝在C
- 7. 深拷貝
- 8. 深拷貝userControl
- 9. 淺拷貝和深拷貝示例
- 10. 使用追加方法的Python淺拷貝和深拷貝
- 11. 深拷貝(鏈表)
- 12. DPDK mbuf深拷貝
- 13. NSManagedObjects深拷貝NSMutableArray
- 14. java的深拷貝
- 15. 深拷貝ASP.NET GridView
- 16. 結構深拷貝
- 17. 懶惰的拷貝 - 如何從淺拷貝創建深層拷貝
- 18. React中的深層拷貝
- 19. Android JetCreator深度拷貝錯誤
- 20. python多處理參數:深拷貝?
- 21. 在python中複製列表:深與淺拷貝:gotcha在python中對我?
- 22. 如何克隆(深層拷貝)java linkList
- 23. 如何深拷貝無符號長
- 24. java克隆深拷貝HashMap
- 25. JavaScript深拷貝使用JSON
- 26. Groovy深拷貝JSON映射
- 27. 深拷貝參考類型
- 28. 深拷貝2維數組
- 29. WPF「撤銷」深拷貝
- 30. C++ boost深層拷貝:: shared_ptr
你爲什麼想這樣做?請注意,隊列不是用作數據結構。 – kennytm 2010-07-31 07:11:39