Python for Network Engineers

How to Sort Vlans

by: George El., January 2019, Reading time: 1 minute

Recently I had a list of iterface vlans, that I wanted to sort. First I tried the sorted method but this didn’t work. Lets have a look:

>>> l=['vlan101','vlan201','vlan1','vlan2','vlan3','vlan4','vlan10','vlan11','vlan102','vlan202','vlan301','vlan302']

>>> for vlan in sorted(l):
...     print(vlan)
...
vlan1
vlan10
vlan101
vlan102
vlan11
vlan2
vlan201
vlan202
vlan3
vlan301
vlan302
vlan4

You see? they are treated as strings. so what can I do? I can pass a sort function as key that will return only the numbers from each vlan. then this will work.

>>> import re
>>> for vlan in sorted(l, 
        key=lambda x: int(re.findall(r'\d+$',x)[0])):
...     print(vlan)
...
vlan1
vlan2
vlan3
vlan4
vlan10
vlan11
vlan101
vlan102
vlan201
vlan202
vlan301
vlan302
>>>

First I import the regular expressions module. Then I search for one or more digits from the end. That is the \d+$ does. Then I get the first element of the array, because findall returns an array and finally convert it to integet. Now the sorted function will use this return value for sorting.

comments powered by Disqus