T
Tim Chase
I've got a large heapq'ified list and want to walk it in-order
without altering it. I get the "unsorted" heap'ish results if I just
do
from heapq import heappush, heappop, nlargest, nsmallest
my_heap = []
for thing in lots_of_items():
heappush(thing)
for item in my_heap:
...
To get them in-order, I can do something like
while my_heap:
item = heappop(my_heap)
do_something(item)
to iterate over the items in order, but that destroys the original
heap. I can also do
for item in nlargest(len(my_heap), my_heap): # or nsmallest()
do_something(item)
but this duplicates a potentially large list according to my
reading of the description for nlargest/nsmallest[1]. Is there a
handy way to non-destructively walk the heap (either in-order or
reversed) without duplicating its contents?
-tkc
[1] http://docs.python.org/2/library/heapq.html#heapq.nlargest
without altering it. I get the "unsorted" heap'ish results if I just
do
from heapq import heappush, heappop, nlargest, nsmallest
my_heap = []
for thing in lots_of_items():
heappush(thing)
for item in my_heap:
...
To get them in-order, I can do something like
while my_heap:
item = heappop(my_heap)
do_something(item)
to iterate over the items in order, but that destroys the original
heap. I can also do
for item in nlargest(len(my_heap), my_heap): # or nsmallest()
do_something(item)
but this duplicates a potentially large list according to my
reading of the description for nlargest/nsmallest[1]. Is there a
handy way to non-destructively walk the heap (either in-order or
reversed) without duplicating its contents?
-tkc
[1] http://docs.python.org/2/library/heapq.html#heapq.nlargest