1

I need to sort this list

list = ['16. Michlík', '4. and 65. Bichakhchyan', '15. Pavol']

according to first number of each string. So that output should look like this

list = ['4. and 65. Bichakhchyan', '15. Pavol', '16. Michlík']

This is what I have so far, but it does not work when there is more then one number in string

sorted(list, key=lambda x : x[:x.find(".")])

Can you guys help me, please?

P. May
  • 95
  • 1
  • 8

3 Answers3

3

You must cast the pattern to an integer, otherwise it is compared as a string.

sorted(list, key=lambda x : int(x[:x.find(".")]))
Olivier Melançon
  • 20,340
  • 3
  • 37
  • 69
1

You can use regex:

import re
l = ['16. Michlík', '4. and 65. Bichakhchyan', '15. Pavol']
result = sorted(l, key=lambda x:int(re.findall('^\d+', x)[0])) 

Output:

['4. and 65. Bichakhchyan', '15. Pavol', '16. Michlík']
Ajax1234
  • 66,333
  • 7
  • 57
  • 95
  • 1
    You can replace `re.findall('^\d+', x)[0]` with `re.match(r'\d+', x).group()` for some free performance. – Aran-Fey Mar 29 '18 at 22:29
1

This is one way.

lst = ['16. Michlík', '4. and 65. Bichakhchyan', '15. Pavol']

res = sorted(lst, key=lambda x: int(x.split('.')[0]))

# ['4. and 65. Bichakhchyan', '15. Pavol', '16. Michlík']
jpp
  • 147,904
  • 31
  • 244
  • 302