Skip to content

Instantly share code, notes, and snippets.

@exogen
Created March 23, 2010 00:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save exogen/340737 to your computer and use it in GitHub Desktop.
Save exogen/340737 to your computer and use it in GitHub Desktop.
import re
import itertools
key_re = re.compile(r'(.*?)(\d*)$')
def string_key(s):
name, number = key_re.match(s).groups()
return (name, number and int(number))
def group_key((i, (name, number))):
if number != '':
return i - number
return name
def group_numbered_strings(strings, format_str='%s-%s'):
indexed_keys = enumerate(itertools.imap(string_key, strings))
for key, group in itertools.groupby(indexed_keys, group_key):
group = list(group)
first_string = '%s%s' % group[0][1]
if len(group) > 1:
last_string = '%s%s' % group[-1][1]
yield format_str % (first_string, last_string)
else:
yield first_string
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment