0

I have the following list of lists in Python.

[[53.60495722746216, 'Percent Cats'],
 [45.298311033121294, 'Percent Dogs'],
 [1.0967317394165388, 'Percent Horses']]

Now I want the Animal with the highest percentage . In this case the it would be Cats.

How do I sort this structure to get the value out?

2
  • 1
    do you want a single value or the list actually sorted? Commented May 18, 2015 at 13:09
  • Here's a simple how to sort guide for Python: docs.python.org/2.7/howto/sorting.html . The same techniques also work for min(), max(), nsmallest(), nlargest(), and groupby() from the heapq and itertools modules. Commented Aug 11, 2015 at 14:57

2 Answers 2

8

You don't need to sort the list if you only need to get one value. Use the built-in max function with custom ordering function like this

In [3]: max(l, key=lambda x: x[0])[1] # compare first elements of inner lists
Out[3]: 'Percent Cats'

or even

In [4]: max(l)[1] # compare lists directly
Out[4]: 'Percent Cats'

The latter code will work as well, because sequence objects may be compared to other objects with the same sequence type:

The comparison uses lexicographical ordering: first the first two items are compared, and if they differ this determines the outcome of the comparison; if they are equal, the next two items are compared, and so on, until either sequence is exhausted. If all items of two sequences compare equal, the sequences are considered equal.

Sign up to request clarification or add additional context in comments.

Comments

0
a = [[53.60495722746216, 'Percent Cats'], [45.298311033121294, 'Percent Dogs'], [1.0967317394165388, 'Percent Horses']]
print sorted(a, key=lambda x:x[0], reverse=True)[0]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.