Created
March 23, 2010 00:52
-
-
Save exogen/340737 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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