[2,3,4,7] --> "2-4,7" ?
andrew cooke
andrew at acooke.org
Thu May 29 20:29:43 EDT 2003
(borrowing r hettinger's neat list comprehension):
import re
numb = re.compile('(\D*)(\d*)')
def group ((list, (last, start, end)), (next, num)):
if last == next:
if int(num) == int(end)+1: return (list, (last, start, num))
if num == start: return (list, (next, num, num))
return (list+[(last, start, end)], (next, num, num))
def fmt ((text, start, end)):
if start == end: return text + start
else: return text + start + "-" + end
def compare ((t1, n1), (t2, n2)):
try: return cmp(t1, t2) or cmp(int(n1), int(n2))
except: return 1
def tidy (list):
if list:
pairs = [numb.match(n).groups() for n in list]
pairs.sort(compare)
(text, num) = pairs[0]
(groups, last) = reduce (group, pairs, ([], (text, num, num)))
return map (fmt, groups+[last])
else: return list
print tidy(['6','7','mx8','mx09','mx10','8','9','10','foo'])
andrew
--
http://www.acooke.org
More information about the Python-list
mailing list