counting occurrences
Grant Griffin
not.this at seebelow.org
Sat Aug 4 00:58:50 EDT 2001
Quinn Dunkan wrote:
>
> On 3 Aug 2001 13:47:34 -0700, Grant Griffin <not.this at seebelow.org> wrote:
> >This then usually leads to a need to "sort keys by value"--something like this:
> >
> > itemlist = [(value, key) for (key, value) in counter.items()]
> > itemlist.sort()
> > itemlist.reverse()
> ...
> >For me, this sort of thing comes up so often that it qualifies as an "idiom".
>
> So put it in a function.
I not sure that a function helps much unless I also make a module for
the function to permanently live in--and this is one of those things
that seems too simple to make into a module, yet too complicated to type
repeatedly. (Hard to please, ain't I?<wink>)
> >...But, among
> >other things, my friend (who has been using Python for a *long* time) said
> >that he has never wanted such a thing, because he doesn't see counting
> >occurrences "as a dictionary operation".
> >
> >So how do you think he does it?
>
> Here's how I would probably do it:
>
> def occurrences(pred, seq):
> # (t -> Boolean) -> [t] -> [(Int, t)]
> d = {}
> for elt in seq:
> if pred(elt):
> d[elt] = d.get(elt, 0) + 1
> a = [ (v, k) for (k, v) in d.items() ]
> a.sort()
> a.reverse()
> return a
Aside from being more neatly packaged, that's really about the same as
mine. Specifically, it's still "a dictionary operation".
I guess I can't think of any easier way to do this in Python than as to
use dictionaries--in one form or another.
thanks-anyway-ly y'rs,
=g2
--
_____________________________________________________________________
Grant R. Griffin g2 at dspguru.com
Publisher of dspGuru http://www.dspguru.com
Iowegian International Corporation http://www.iowegian.com
More information about the Python-list
mailing list