Consider the following:
p1=1;
p2=5;
p3=7;
highest=max(p1,p2,p3).
The max function would return 7. I am looking to create a similar function, which would return “p3”. I have created a small function (by simple comparisons) for the above example, shown below. however I am having trouble when the number of arguments go up.
def highest(p1,p2,p3):
if (p1>p2) and (p1>p3):
return "p1"
if (p2>p1) and (p2>p3):
return "p2"
if (p3>p1) and (p3>p1):
return "p3"
Is there a simpler way to do this>
Update: Paul Hankin pointed out that max() took a key function, which I didn’t know. So:
Other solutions for completeness:
In Python 2.7 and 3.x you can use dictionary comprehensions.
Dictionary comprehensions are neat. 🙂
In earlier versions of Python you can do this:
Which will work in anything after Python 2.2 or so.