-1

I have a list of string like this:

a = ["part 1", "part 3" , "part 10", "part 2"....]

If I sort them and print, sorted[a]the result is

["part 1", "part 10", "part 2", "part 3"]

But I want to sort them as:

["part 1", "part 2", "part 3", "part 10"]

by the numeric value in each string. How can I implement that? Thanks

manxing
  • 3,165
  • 12
  • 45
  • 56
  • 2
    Dup: [Does Python have a built in function for string **natural sort**?](http://stackoverflow.com/questions/4836710/does-python-have-a-built-in-function-for-string-natural-sort) – Ashwini Chaudhary Dec 09 '13 at 12:32

1 Answers1

4
a = ["part 1", "part 3" , "part 10", "part 2"]
print sorted(a, key=lambda x:int(x.split()[1]))

Output

['part 1', 'part 2', 'part 3', 'part 10']

If you want to sort in-place,

a.sort(key=lambda x:int(x.split()[1]))
print a
thefourtheye
  • 233,700
  • 52
  • 457
  • 497