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

Alexander Schmolck a.schmolck at gmx.net
Thu May 29 18:17:27 EDT 2003


George Young <gry at ll.mit.edu> writes:

> [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?

Not really:

import re
def compressRanges(l):
    if not l: return ""
    prefixNumStrTuples = [re.match(r'(\D*)(\d*)', s).groups() for s in l]
    lastPrefix, lastNumS = prefixNumStrTuples.pop(0)
    startNumS = lastNumS
    startNum = lastNum = lastNumS and int(lastNumS)
    prefixNumStrTuples.append(("",""))
    res = []
    for prefix, numS in prefixNumStrTuples:
        num = numS and int(numS)
        if prefix != lastPrefix or numS and lastNum != num - 1:
            if startNum != lastNum:
                res.append(lastPrefix + startNumS + '-' + lastNumS)
            else:
                res.append(lastPrefix + lastNumS)
            startNum, startNumS = num, numS
        lastNum, lastNumS = num, numS
        lastPrefix = prefix
    return ','.join(res)

'as





More information about the Python-list mailing list