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 a list that contains both strings and integers (Python)

I want to sort a list of tuples which contain (string, integer, integer). The first value of these tuples can be any string (for example ‘$’, or a numeric string such as ‘9’). The goal is to sort according to the first element of these tuples, if the comparison occurs between two identical strings I sort according to the second element. I tried the following approach but it turned out to be unsuccessful. Solutions?

array = [('$', 0, 0), ('3', 3, 3), ('7', 5, 6), ('15', 6, 9), ('5', 7, 11), ('17', 8, 13), ('18', 9, 16), ('19', 10, 18), ('16', 11, 20)]
sorted_array = sorted(array, key=lambda x:(x[0], int(x[1])))
print(sorted_array)

Output:

[('$', 0, 0), ('3', 3, 3), ('7', 5, 6), ('15', 6, 9), ('5', 7, 11), ('17', 8, 13), ('18', 9, 16), ('19', 10, 18), ('16', 11, 20)]

I want to get:

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

[('$', 0, 0), ('3', 3, 3), ('5', 7, 11), ('7', 5, 6), ('15', 6, 9), ('16', 11, 20), ('17', 8, 13), ('18', 9, 16), ('19', 10, 18)]

>Solution :

Using natsort (natural sorting) and str.isdigit you can sort numbers naturally while keeping non numbers first. But the more general rule you might expect is unclear.

from natsort import natsorted 

array = [('$', 0, 0), ('3', 3, 3), ('7', 5, 6), ('15', 6, 9), ('5', 7, 11), ('17', 8, 13), ('18', 9, 16), ('19', 10, 18), ('16', 11, 20)]
sorted_array = natsorted(array, key=lambda x:(x[0].isdigit(), x))
print(sorted_array)

Output:

[('$', 0, 0), ('3', 3, 3), ('5', 7, 11), ('7', 5, 6), ('15', 6, 9), ('16', 11, 20), ('17', 8, 13), ('18', 9, 16), ('19', 10, 18)]
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