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']
1
  • 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 Commented Nov 27, 2018 at 11:26

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

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!)
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...
@JonClements Wow ok I had absolutely no idea rstrip performed like that... TIL
3

Split on (.) and convert to int

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

1 Comment

Use of os.path.splitext would be more correct here.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.