extracting a heapq in a for loop - there must be more elegant solution
__peter__ at web.de
Tue Dec 3 13:38:58 CET 2013
Helmut Jarausch wrote:
> I'd like to extracted elements from a heapq in a for loop.
> I feel my solution below is much too complicated.
> How to do it more elegantly?
> I know I could use a while loop but I don't like it.
> Many thanks for some lessons in Python.
> Here is my clumsy solution
> from heapq import heappush, heappop
> # heappop raises IndexError if heap is empty
> for N in 'H','C','W','I' :
H = ["H", "C", "W", "I"]
But see below.
> # how to avoid / simplify the following function
> def in_sequence(H) :
> try :
> while True :
> N= heappop(H)
> yield N
> except IndexError :
> raise StopIteration
> # and here the application:
> for N in in_sequence(H) :
If you are iterating over the complete heap I see no advantage over a sorted
for N in sorted(H):
If H is huge use H.sort() instead of sorted() to save memory.
If you need only a few items use heapq.nsmallest().
More information about the Python-list