On Mar 29, 8:49 am, [EMAIL PROTECTED] (Alex Martelli) wrote: > Ben Finney <[EMAIL PROTECTED]> 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
This doesn't call foo.count for duplicate entries by keeping a cache >>> foo = ["spam", "eggs", "spam", "spam", "spam", "beans", "eggs"] >>> def cachecount(x, cache={}): ... return cache.setdefault(x, foo.count(x)) ... >>> max(foo, key=cachecount) 'spam' >>> cachecount.func_defaults ({'eggs': 2, 'beans': 1, 'spam': 4},) >>> - Paddy. -- http://mail.python.org/mailman/listinfo/python-list