4

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!

0

3 Answers 3

5

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.

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

1 Comment

Seems to be the best solution. Thank you very much!
3

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

1 Comment

Thank i'll try this!
2
# read list in from memory and store as variable file_list
sorted(file_list, key = lambda x: map(int, x.split('.')[:-1]))

In case you're wondering what is going on here:

Our lambda function first takes our filename, splits it into an array delimited by periods. Then we take all of the elements of the list, minus the last element, which is our file extension. Then we apply the 'int' function to every element of the list. The returned list is then sorted by the 'sorted' function according to the elements of the list, starting at the first with ties broken by later elements in the list.

1 Comment

The [:-1] takes care of all file extensions, not just .py. And using map with int on the split. +1 for those.

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.