itertools.groupby
Steve Howell
showell30 at yahoo.com
Mon May 28 10:43:37 EDT 2007
--- Raymond Hettinger <python at rcn.com> wrote:
> + The operation of \function{groupby()} is similar
> to the \code{uniq}
> filter
> + in \UNIX{}. [...]
Thanks!
The comparison of groupby() to "uniq" really clicks
with me.
To the extent that others like the Unix command line
analogy for understanding Python idioms, I compiled
the following list, which includes a couple groupby
examples from Raymond.
>>> 'abacadabra'[:5] # head -5
abaca
>>> 'abacadabra'[-5:] # tail -5
dabra
>>> [word for word in 'aaa,abc,foo,zzz,cba'.split(',')
if 'a' in word] # grep a
['aaa', 'abc', 'cba']
>>> sorted('abracadabra') # sort
['a', 'a', 'a', 'a', 'a', 'b', 'b', 'c', 'd', 'r',
'r']
>>> list(reversed(sorted('abracadabra'))) # sort -r
['r', 'r', 'd', 'c', 'b', 'b', 'a', 'a', 'a', 'a',
'a']
>>> [k for k, g in groupby(sorted('abracadabra'))] #
sort | uniq
['a', 'b', 'c', 'd', 'r']
>>> [(k, len(list(g))) for k, g in
groupby(sorted('abracadabra'))] # sort | uniq -c
[('a', 5), ('b', 2), ('c', 1), ('d', 1), ('r', 2)]
>>> [k for k, g in groupby(sorted('abracadabra')) if
len(list(g)) > 1] # sort | uniq -d
['a', 'b', 'r']
____________________________________________________________________________________Get the Yahoo! toolbar and be alerted to new email wherever you're surfing.
http://new.toolbar.yahoo.com/toolbar/features/mail/index.php
More information about the Python-list
mailing list