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']
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.
Split on (.) and convert to int
sorted(a, key=lambda x: int(x.split('.')[0]))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With