Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #9935
| References | <acfc6e53-fd3c-4404-9314-aa01dc35c0d7@a31g2000vbt.googlegroups.com> |
|---|---|
| Date | 2011-07-19 21:33 -0700 |
| Subject | Re: Pythonic way with more than one max possible |
| From | Chris Rebert <clp2@rebertia.com> |
| Newsgroups | comp.lang.python |
| Message-ID | <mailman.1278.1311136401.1164.python-list@python.org> (permalink) |
On Tue, Jul 19, 2011 at 8:17 PM, CM <cmpython@gmail.com> wrote:
> I have three items in a dict, like this:
>
> the_dict = {'a':1, 'b':2, 'c':3}
>
> but the vals could be anything. I want to configure something else
> based on the "winner" of such a dict, with these rules:
>
> 1. In this dict, if there is a UNIQUE max value, that's the winner.
> 2. If there are any TIES for max value, b is the winner by default.
Er, for (2), you mean b's /value/ is the winner, right?
> The problem for me, as I see it, is I don't know any elegant ways to
> do this in Python. The max(dict) function doesn't distinguish between
> unique and non-unique maxes. I could go through and test the various
> possibilities (to see if the max value had any matches in the other
> values), but, knowing Python, there is probably something close to
> "one way to do it". Any suggestions?
# presumes at least 2 items
from heapq import nlargest
winner, runner_up = nlargest(2, the_dict.itervalues())
if winner == runner_up:
winner = the_dict['b']
Cheers,
Chris
--
http://rebertia.com
Back to comp.lang.python | Previous | Next — Previous in thread | Next in thread | Find similar | Unroll thread
Pythonic way with more than one max possible CM <cmpython@gmail.com> - 2011-07-19 20:17 -0700
Re: Pythonic way with more than one max possible Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2011-07-20 14:19 +1000
Re: Pythonic way with more than one max possible Thomas Jollans <t@jollybox.de> - 2011-07-20 12:51 +0200
Re: Pythonic way with more than one max possible Chris Rebert <clp2@rebertia.com> - 2011-07-19 21:33 -0700
Re: Pythonic way with more than one max possible CM <cmpython@gmail.com> - 2011-07-19 22:10 -0700
Re: Pythonic way with more than one max possible woooee <woooee@gmail.com> - 2011-07-19 22:37 -0700
Re: Pythonic way with more than one max possible Chris Rebert <clp2@rebertia.com> - 2011-07-19 23:56 -0700
Re: Pythonic way with more than one max possible CM <cmpython@gmail.com> - 2011-07-20 13:25 -0700
csiph-web