Home > Back-end >  Sorting a list of strings in python on regex isnt actually sorted
Sorting a list of strings in python on regex isnt actually sorted

Time:04-17

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

CodePudding user response:

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])

CodePudding user response:

As others already mentioned, you need to return a single element from the function that has been passed to the key parameter. (not a list which is returned from findall). That element is going to be used for sorting.

You can get the first item from the findall or change findall to search and grab the first group. Don't forget to convert the final result to integer.

import re

lst = [' 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 int(re.search(r'ile: (\d )', elem).group(1))

lst = sorted(lst, key=ile_sort)
print(lst)

output:

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