Search code examples
pythonversioning

How to sort list of version tags in Python


I have a list with tags like this:

list = ['1.0.0','1.0.1','1.1.1','1.1.1.abc','2.20.11','2.0.10.abc2']

I want to sort it base on the first number, then second number, then third.

The output should be like this:

['1.0.0','1.0.1','1.1.1','1.1.1.abc','2.0.10.abc2','2.20.11']

I've tried to use sort like this:

list.sort(key=lambda x: (x[:x.find('.')], int(x[x.find('.')+1:x.index('.',x.find('.')+1)]) ) )

I can sort base on the first two numbers just fine, it's the third number that bothers me, because there might be a string part, and also the numbers might be two digits or more, I don't know how to exclude the last string part and only sort the numbers.

Any Ideas on this?

Edit

The problem with default sort is that, I wouldn't properly sort all the parts, for example it would put 4.35.7 before 4.9.2 for some reason, that why I need to explicitly sort base on each part. My problem is that there might be a string part followed by numbers.


Solution

  • You can use sorted with a key.

    You indeed need to use str.split to split the string into tokens. This will allow you to rely on list ordering.

    Although, you will need to cast strings of digits to int first to get the expected result, otherwise numbers will be sorted in alphabetical order instead of numercial order.

    Example

    l = ['1.0.0','1.0.1','1.1.1','1.1.1.abc','2.20.11','2.0.10.abc2']
    sorted_l = sorted(l, key=lambda x: [int(i) if i.isdigit() else i for i in x.split('.')])
    

    Output

    ['1.0.0', '1.0.1', '1.1.1', '1.1.1.abc', '2.0.10.abc2', '2.20.11']