superformula
superformula

Reputation: 3

Sort lists by second smallest element

I have a list of lists

lists=[["John",8,7,9],["Sarah",5,3,8],["David",4,3,9],["Alice",5,4,7]]

which I want to sort by their smallest element, but if that element is the same, I want to perform a secondary sort by the second smallest element. So far I've sorted by the first criterion:

lists.sort(key=lambda x: min(x))

which, when I call lists returns

[["Sarah",5,3,8],["David",4,3,9],["Alice",5,4,7],["John",8,7,9]]

and now I want to put ["David",4,3,9] ahead of ["Sarah",5,3,8] but I don't know how to refer to the second smallest element. Thanks in advance!

Upvotes: 0

Views: 88

Answers (1)

Moinuddin Quadri
Moinuddin Quadri

Reputation: 48067

Use sorted instead of min within the lambda expression as:

>>> lists=[["John",8,7,9],["Sarah",5,3,8],["David",4,3,9],["Alice",5,4,7]]

#        sort based on numeric values v
>>> lists.sort(key=lambda x: sorted(x[1:]))
>>> lists
[['David', 4, 3, 9], ['Sarah', 5, 3, 8], ['Alice', 5, 4, 7], ['John', 8, 7, 9]]

It will sort your list based on the order of the values in increasing order.

Upvotes: 1

Related Questions