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

Sorting a list of strings in python on regex isnt actually sorted

So i have a list of strings and im sorting it with:

list = [' R1O-GN | ile: 13 |', ' LXQ2-T | ile: 6 |', ' LXQ2-T | ile: 11 |', ' LXQ2-T | ile: 9 |', ' 4-HWWF | ile: 11 |', ' 4-HWWF | ile: 9 |', ' J-ZYSZ | ile: 12 |', ' UGR-J2 | ile: 8 |']

def ile_sort(elem):
    return re.findall(r'ile: (\d+)',elem)

list = sorted(list, key=ile_sort)

String with 6 should be first and one with 13 last, but the actual result is:

[' LXQ2-T | ile: 11 |', ' 4-HWWF | ile: 11 |', ' J-ZYSZ | ile: 12 |', ' R1O-GN | ile: 13 |', ' LXQ2-T | ile: 6 |', ' UGR-J2 | ile: 8 |', ' LXQ2-T | ile: 9 |', ' 4-HWWF | ile: 9 |']

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

>Solution :

The problem is that using re.findall() on those list items returns a string within a list, such as this: ["13"]

To combat this, replace your ile_sort() method with this:

def ile_sort(elem):
    return int(re.findall('ile: (\d+)', elem)[0])
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