Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - sort list

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']
like image 898
Omkar Avatar asked Jun 05 '26 00:06

Omkar


2 Answers

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.

like image 83
TerryA Avatar answered Jun 07 '26 12:06

TerryA


Split on (.) and convert to int

sorted(a, key=lambda x: int(x.split('.')[0]))
like image 26
min2bro Avatar answered Jun 07 '26 14:06

min2bro



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!