[2,3,4,7] --> "2-4,7" ?

George Young gry at ll.mit.edu
Thu May 29 15:11:21 EDT 2003


[python 2.3a1]
I have a list of "names" like:
  ['6','7','mx8','mx09','mx10','8','9','10','foo']
which needs for concise and clear display to become a string like:

  "6-7,mx8-10,8-10,foo"

I.e., a name is an integer or an alphabetic prefix possibly followed
by an integer.  The display must compress each set of succesive names
having the same (possibly null) prefix and sequential integers.  The
original order of names must be preserved.

I (hesitantly) post the following code that works, but makes me cringe
anytime I see it, for it's clumsy unreadableness.  Can someone with
a fresh mind see a clear and concise way to make my clear and concise
name display?


names = ['6','7','mx8','mx09','mx10','8','9','10','foo']
groups = []
import re

def collapse(x,y):
    if x and x[-1][1] and y[1] and x[-1][0] == y[0] and int(x[-1][2]) == (int(y[2])-1):            x[-1][2] = y[2]
            return x
    else:
        x.append(y)
        return x

groups = []
for n in names:
    r = re.compile('\d*$').search(n)
    groups.append([n[0:r.start()], n[r.start():r.end()], n[r.start():r.end()]])

r = reduce(collapse, groups, [])
s=[]
for i in r:
    if i[1] == i[2]:
        n=i[1]
    else:
        n=i[1] + '-' + i[2]
    s.append(i[0] + n)

print ','.join(s)





More information about the Python-list mailing list