Modal value of an array

Alex Martelli aleax at mac.com
Thu Mar 29 03:49:14 EDT 2007


Ben Finney <bignose+hates-spam at benfinney.id.au> wrote:
   ...
> That's not the only case though. What do you expect to be returned for
> an input of ["eggs", "beans", "beans", "eggs", "spam"] ?
> 
> Assuming you want *a* mode value, and any one will do (e.g. any of
> "spam", "eggs" or "beans" is okay), I'd write it this way as a first
> guess:
> 
>     >>> foo = ["spam", "eggs", "spam", "spam", "spam", "beans", "eggs"]
>     >>> counts = [(foo.count(val), val) for val in set(foo)]
>     >>> counts
>     [(2, 'eggs'), (1, 'beans'), (4, 'spam')]
>     >>> sorted(counts)[-1]
>     (4, 'spam')
>     >>> sorted(counts)[-1][1]
>     'spam'

A bit more directly:

>>> foo = ["spam", "eggs", "spam", "spam", "spam", "beans", "eggs"]
>>> max(foo, key=foo.count)
'spam'


Alex



More information about the Python-list mailing list