Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[['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']]

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading