Skip to content

Instantly share code, notes, and snippets.

@skamithi
Last active August 29, 2015 14:01
Show Gist options
  • Save skamithi/fa3811f9419653f6329b to your computer and use it in GitHub Desktop.
Save skamithi/fa3811f9419653f6329b to your computer and use it in GitHub Desktop.
python convert list of numbers into ranges.
import re
from itertools import groupby
from collections import OrderedDict
# define list of interfaces
a = ['swp2100', 'bond12.100', 'swp22', 'br20',
'bond0', 'bond22', 'port-channel5']
b = OrderedDict()
# group ports based on int name before digit
f = lambda x: re.match(r'([a-z_-]+)\d+', x.lower()).group(1)
gb = groupby(a, f)
for k, a in gb:
try:
b[k] = b[k] + map(str, a)
except:
b[k] = map(str, a)
"create a new dict with sorted keys"
newdct = OrderedDict((key, b[key]) for key in sorted(b.keys()))
print newdct
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment