Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort list with multiple criteria in python

Currently I'm trying to sort a list of files which were made of version numbers. For example:

0.0.0.0.py
1.0.0.0.py
1.1.0.0.py

They are all stored in a list. My idea was to use the sort method of the list in combination with a lambda expression. The lambda-expression should first remove the .py extensions and than split the string by the dots. Than casting every number to an integer and sort by them.

I know how I would do this in c#, but I have no idea how to do this with python. One problem is, how can I sort over multiple criteria? And how to embed the lambda-expression doing this?

Can anyone help me?

Thank you very much!

like image 310
BendEg Avatar asked Dec 25 '22 09:12

BendEg


2 Answers

You can use the key argument of sorted function:

filenames = [
    '1.0.0.0.py',
    '0.0.0.0.py',
    '1.1.0.0.py'
]

print sorted(filenames, key=lambda f: map(int, f.split('.')[:-1]))

Result:

['0.0.0.0.py', '1.0.0.0.py', '1.1.0.0.py']

The lambda splits the filename into parts, removes the last part and converts the remaining ones into integers. Then sorted uses this value as the sorting criterion.

like image 131
JuniorCompressor Avatar answered Jan 08 '23 18:01

JuniorCompressor


Have your key function return a list of items. The sort is lexicographic in that case.

l = [ '1.0.0.0.py', '0.0.0.0.py', '1.1.0.0.py',]
s = sorted(l, key = lambda x: [int(y) for y in x.replace('.py','').split('.')])
print s
like image 39
Robᵩ Avatar answered Jan 08 '23 18:01

Robᵩ