user1042305
user1042305

Reputation: 1

Sort list of lists by multiple values in Python

I need to sort a list of lists, where each entry in the outer list is a list of three integers like this:

[[3,1,0],[1,2,3],[3,2,0],[3,1,1]]

The trick is that I need to sort it by entry[0], and if there's a tie, then sort them by entry[1], and if that's also a tie, sort by entry[2], so the list above should be:

[[3,2,0],[3,1,1],[3,1,0],[1,2,3]]

I keep overthinking my loops and sort statements and I haven't been able to get a way to check the entries in order without rearranging my lists by those values instead of keeping the hierarchy.

Any suggestions?

Upvotes: 0

Views: 661

Answers (1)

Cat Plus Plus
Cat Plus Plus

Reputation: 129764

It's a default behaviour for comparing lists.

x = [[3,1,0],[1,2,3],[3,2,0],[3,1,1]]
x.sort(reverse = True)
print(x)

Upvotes: 8

Related Questions