Explanation
You are trying to sort a list of strings. Strings are naturally sorted in lexicographical_order, i.e. "10" < "11" < "2" < "5" < ...
, so Python executes correctly what you want it to do. This being said, you need to transform your data into something that will be sorted as you want.
Solution
>>> a = ['1/1/11', '1/1/6']
>>> a
['1/1/11', '1/1/6']
>>> def to_tuple(string_representation):
... return tuple(int(i) for i in string_representation.split('/'))
...
>>> b = [to_tuple(element) for element in a]
>>> b.sort()
>>> b
[(1, 1, 6), (1, 1, 11)]
>>> a.sort(key=to_tuple)
>>> a
['1/1/6', '1/1/11']
Here we use the fact that tuple is sorted by default exactly how we want it to be sorted in your case (actually, it is also a lexicographical order, but now 11
is one element of a sequence and not two).
List b
contains a transformed list, where each element is a tuple
. And now sort
will work as you want.
The second option, will be using a custom key
operator. It is a function that returns a key to compare different elements of your list. In this case, key will be a corresponding tuple
of integers and will be compared as you want.
Note 1
The second approach (with the key
operator) will create an additional overhead during sorting as it will be called O(NlogN)
times.
Note 2
You also tried using the result of sort
function as a value, but it changes the given list in-place. If you want a sorted copy of your list, use sorted.