-1

How do I sort this list numerically?

sa = ['3 :mat', '20 :zap', '20 :jhon', '5 :dave', '14 :maya' ]
print(sorted(sa))

This shows

[ '14 :maya', '20 :zap','20 :jhon', '3 :mat', '5 :dave']
shahidammer
  • 1,026
  • 2
  • 10
  • 24
  • 3
    Does this answer your question? [How to sort alpha numeric set in python](https://stackoverflow.com/questions/2669059/how-to-sort-alpha-numeric-set-in-python) – DarrylG Jul 02 '20 at 10:59

3 Answers3

0

You can do it like this, since your numbers are part a the string:

sorted(sa, key = lambda x: int(x.split(' ')[0]))
Jonas
  • 1,749
  • 1
  • 10
  • 18
0

You can do something like the below, which will use the numbers in the string and sort them.

sa.sort(key=lambda x: int(''.join(filter(str.isdigit, x))))
print(sa)
shahidammer
  • 1,026
  • 2
  • 10
  • 24
0

using regex:

sorted(sa, key=lambda x:int(re.findall('\d+', x)[0]))

['3 :mat', '5 :dave', '14 :maya', '20 :zap', '20 :jhon']

Using module natsort

from natsort import natsorted
natsorted(sa)

['3 :mat', '5 :dave', '14 :maya', '20 :jhon', '20 :zap']
Pygirl
  • 12,969
  • 5
  • 30
  • 43