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']]
CodePudding user response:
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.