1

I'm new to python automation and wrote a script to get some port handles from Ixia and store into a list. I;m trynig to sort that port-handle where I see a problem.

I tried using the sort method but doesn;t work

>>> a
['1/1/11', '1/1/6']
>>> a.sort()
>>> a
['1/1/11', '1/1/6']
>>> d = a.sort()
>>> print(d)
None
>>>

Am i missing anything here .. kindly clarify

I want the output in the following format

1/1/6 1/1/11
VijayS
  • 81
  • 4

1 Answers1

1

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.

Valeriy Savchenko
  • 1,524
  • 8
  • 19