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

Mike C. Fletcher mcfletch at rogers.com
Thu May 29 15:56:23 EDT 2003


This might be a little easier to read (though actually less concise), 
though I haven't tried to follow your code to figure out if it's exactly 
equivalent.  I also haven't bothered with re-formatting the groups into 
range statements, I leave them as data-records from which you can easily 
create the range statements:

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

def collapse( names ):
    """Collapse ranges of names"""
    result = []
    current = []
    currentPrefix = ''
    for item in names:
        a,b = split( item )
        if a == currentPrefix and current and b == current[-1]+1:
            current.append( b )
        else:
            if current:
                # need to put previous result in result-set
                result.append( (currentPrefix,current))
            # now process the new item...
            if b is None:
                # no number, so just add record to list
                result.append( (a,[]))
                current = []
            else:
                current = [b]
            currentPrefix = a
    if current:
        result.append( (currentPrefix,current))
    return result
           

matcher = re.compile( '^(?P<prefix>\D*)(?P<number>\d*)$' )
   
def split( s ):
    """Get prefix and integer value (or None) for a string"""
    a,b = matcher.match( s ).groups()
    if b:
        b = int( b, 10 )
    return a, b or None

print collapse( names )

Enjoy,
Mike


George Young wrote:

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

_______________________________________
  Mike C. Fletcher
  Designer, VR Plumber, Coder
  http://members.rogers.com/mcfletch/








More information about the Python-list mailing list