frank verkoren
frank verkoren

Reputation: 3

sort my python list based on multiple values

I want to sort lists as the following:

input:

mylist = [['12','25'],['4','7'],['12','14']]

output:

[['4','7'],['12','14'],['12','25']]

the current code that I use only sorts the first number of the lists:

def defe(e):
   return int(e[0])
mylist = [['12','25'],['4','7'],['12','14']]
mylist.sort(key=defe)
print(mylist)

output:

[['4','7'],['12','25'],['12','14']]

Upvotes: 0

Views: 632

Answers (1)

user7864386
user7864386

Reputation:

Try:

sorted(mylist, key=lambda x: (int(x[0]), int(x[1])))

Output:

[['4', '7'], ['12', '14'], ['12', '25']]

If sublists are longer than 2, then

sorted(mylist, key=lambda x: list(map(int, x)))

is better.

Upvotes: 3

Related Questions