0

I have a list of string containing numbers like this:

['line_1.jpg Word930\n', 'line_10.jpg Word203\n', 'line_2.jpg Word31\n', 'line_100.jpg Word7\n',  'line_3.jpg Word60\n', 'line_4.jpg Word52\n']

I want to sort the numbers in the string before the space in each string from small to large,I want this result:

['line_1.jpg Word930\n', 'line_2.jpg Word31\n', 'line_3.jpg Word60\n',
'line_4.jpg Word52\n', 'line_10.jpg Word203\n', 'line_100.jpg Word7\n']

I use this code to sort list:

myList=['line_1.jpg Word930\n', 'line_10.jpg Word203\n', 'line_2.jpg Word31\n', 'line_100.jpg Word7\n',  'line_3.jpg Word60\n', 'line_4.jpg Word52\n']
myList.sort()
print(myList)

But the result is:

['line_1.jpg Word930\n', 'line_10.jpg Word203\n', 'line_100.jpg Word7\n', 'line_2.jpg Word31\n', 'line_3.jpg Word60\n', 'line_4.jpg Word52\n']

This is not right,how to fix the code?

RoadRunner
  • 25,803
  • 6
  • 42
  • 75
  • 1) Use [sorted/sort](https://docs.python.org/3/howto/sorting.html) with a key function. 2) Inside the function, extract the number from the string - possibly with a regex and int conversion. There are duplicates on both tasks. – user2864740 May 10 '20 at 06:52
  • already answered => https://stackoverflow.com/questions/5967500/how-to-correctly-sort-a-string-with-a-number-inside – Mr_Zed May 10 '20 at 06:52

3 Answers3

2

You can use re to get the value and use that in the list.sort's keyfunction like,

>>> import re
>>> x
['line_1.jpg Word930\n', 'line_10.jpg Word203\n', 'line_2.jpg Word31\n', 'line_100.jpg Word7\n', 'line_3.jpg Word60\n', 'line_4.jpg Word52\n']
>>> x.sort(key=lambda x: int(re.search(r'line_(\d+).*', x).group(1)))
>>> x
['line_1.jpg Word930\n', 'line_2.jpg Word31\n', 'line_3.jpg Word60\n', 'line_4.jpg Word52\n', 'line_10.jpg Word203\n', 'line_100.jpg Word7\n']
>>> 
han solo
  • 6,390
  • 1
  • 15
  • 19
1

You can sorted the list like

myList.sort(key=lambda x: int(x[x.find("_")+ 1:x.find(".")]))

That will sort the list base on the number of the file.

Leo Arad
  • 4,452
  • 2
  • 6
  • 17
1

We could split the string on "." to get the filename, split again on "_", then get the number from the last item and convert to an integer. Then we can pass this to the key function of sorted().

lst = ['line_1.jpg Word930\n', 'line_2.jpg Word31\n', 'line_3.jpg Word60\n', 'line_4.jpg Word52\n', 'line_10.jpg Word203\n', 'line_100.jpg Word7\n']

print(sorted(lst, key=lambda x: int(x.split(".")[0].split("_")[-1])))
# ['line_1.jpg Word930\n', 'line_2.jpg Word31\n', 'line_3.jpg Word60\n', 'line_4.jpg Word52\n', 'line_10.jpg Word203\n', 'line_100.jpg Word7\n']
RoadRunner
  • 25,803
  • 6
  • 42
  • 75