from heapq import nlargest words = (word for line in open('mystory.txt') for word in
Feedback is requested for two prospective itertools: def count_elements(iterable): b = {} for elem in iterable: b[elem] = b.get(elem, 0) + 1 return ((cnt, elem) for elem, cnt in b.iteritems()) def pairswap(iterable): return ((b,a) for a,b in iterable) The first is designed to provide item counts for min(), max(), sorted(), nlargest(), and nsmallest(). It accepts any iterable including generator expressions: line.split())
nlargest(count_elements(words), 3) [(200, 'super'), (129, 'hero'), (103, 'villain')]
The second handles reordering of fields in tuples of length two. It works well with dict(), enumerate(), dict.iteritems(), itertools.starmap() and anything else that accepts or returns a series of pairs:
list(pairswap(_)) [('super', 200), ('hero', 129), ('villain', 103)]
inversemap = dict(pairswap(forwardmap.iteritems()))
maptoposition = dict(pairswap(enumerate(mysequence)))
Raymond P.S. If you have naming suggestions other than pairswap() and count_elements(), I'm all ears.
participants (11)
-
Aahz
-
Bob Ippolito
-
Brett C.
-
David Abrahams
-
David Eppstein
-
Grégoire Dooms
-
Holger Krekel
-
Josiah Carlson
-
Michael Hudson
-
Raymond Hettinger
-
Raymond Hettinger