Sort list with multiple criteria in python

I'm currently trying to sort the list of files that were made from version numbers. For example:

0.0.0.0.py
1.0.0.0.py
1.1.0.0.py

All of them are stored in the list. My idea was to use a sortlist method in conjunction with a lambda expression. The lambda expression must first remove the extensions .py, and then break the string into dots. What distinguishes each number to an integer and sorts by them.

I know how to do this in C #, but I have no idea how to do this with python. One of the problems is how can I sort by several criteria? And how to include this lambda expression?

Can anybody help me?

Many thanks!

+4
source share
3 answers

You can use the key argument of the function sorted:

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 breaks the file name into parts, removes the last part, and converts the rest to integers. It then sorteduses this value as a sorting criterion.

+5
source

Ask the function keyto return a list of items. In this case, the sorting is lexicographic.

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
+3
source
# read list in from memory and store as variable file_list
sorted(file_list, key = lambda x: map(int, x.split('.')[:-1]))

, :

- , , . , , . "int" . "" , , , .

+2

Source: https://habr.com/ru/post/1626078/


All Articles