[Python-Dev] Candidate Itertools
Raymond Hettinger
raymond.hettinger at verizon.net
Tue Jun 15 04:27:52 EDT 2004
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:
>>> from heapq import nlargest
>>> words = (word for line in open('mystory.txt') for word in
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.
More information about the Python-Dev
mailing list