2

I have a list in this format:

a = ["1.mp4", "10.mp4", "100.mp4", "2.mp4", "20.mp4", "200.mp4"]

I have to sort the above list in ascending order.

My code:

def ascend(a):
    a.sort()
    return a

a = ["1.mp4", "10.mp4", "100.mp4", "2.mp4", "20.mp4", "200.mp4"]
print(ascend(a))

My Output:

['1.mp4', '10.mp4', '100.mp4', '2.mp4', '20.mp4', '200.mp4']

And the actual Output should be

['1.mp4', '2.mp4', '10.mp4', '20.mp4', '100.mp4', '200.mp4']
Netwave
  • 40,134
  • 6
  • 50
  • 93
Omkar
  • 111
  • 1
  • 9
  • 2
    While this is a duplicate, it's useful for OP to understand what's wrong with his code. He has shown an attempt at his problem, and so his question is a valid one nonetheless – TerryA Nov 27 '18 at 11:26

2 Answers2

9

The problem is it's sorting lexicographically not numerically so '10' < '2' in this case. Add a sort key:

>>> a = ["1.mp4", "10.mp4", "100.mp4", "2.mp4", "20.mp4", "200.mp4"]
>>> sorted(a, key=lambda x: int(x[:-4]))
['1.mp4', '2.mp4', '10.mp4', '20.mp4', '100.mp4', '200.mp4']

The key parameter takes in a function, which deals with each element of a. We are telling Python to sort each element by first removing the .mp4 of the string, then converting the string to an integer, and sorting numerically.

TerryA
  • 58,805
  • 11
  • 114
  • 143
  • 1
    `rstrip` hey? Let's hope a filename isn't `444.mp4` then (or anything with 4's immediately preceding ".mp4" - else a nice little subtle sorting error/exception!) – Jon Clements Nov 27 '18 at 11:48
  • So `a = ["1.mp4", "10.mp4", "100.mp4", "24.mp4", "20.mp4", "200.mp4"]` will sort incorrectly, and `a = ['1.mp4', '2.mp4', '10.mp4', '20.mp4', '100.mp4', '200.mp4', '444.mp4']` will raise a `ValueError`... – Jon Clements Nov 27 '18 at 11:51
  • 1
    @JonClements Wow ok I had absolutely no idea `rstrip` performed like that... TIL – TerryA Nov 27 '18 at 14:45
3

Split on (.) and convert to int

sorted(a, key=lambda x: int(x.split('.')[0]))
min2bro
  • 4,509
  • 5
  • 29
  • 55