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
  • 21,584
  • 4
  • 41
  • 73
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
  • 69,937
  • 8
  • 61
  • 102
  • 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
  • 159,742
  • 34
  • 281
  • 339