[2,3,4,7] --> "2-4,7" ?
CezaryB
cezary at nodomain.invalid
Fri May 30 13:52:47 EDT 2003
On 5/29/2003 9:11 PM, 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?
>
from __future__ import nested_scopes
import re
def collapse( input_sequence ):
search = re.compile( '\d+$' ).search
range_prefix = None
range_start = 0
range_last = 0
item_last = None
result_list = []
def append_last( ):
if range_prefix is not None:
if range_start == range_last:
result_list.append( item_last )
else:
result_list.append( range_prefix + str( range_start ) + '-' + str(
range_last ) )
for item in input_sequence:
found = search( item )
if found is None:
append_last( )
result_list.append( item )
range_prefix = None
continue
start = found.start( )
prefix = item[:start]
value = int( item[start:] )
if prefix == range_prefix and value == range_last + 1:
range_last = value
else:
append_last( )
range_prefix = prefix
range_start = value
range_last = value
item_last = item
append_last( )
return ','.join( result_list )
---
CB
More information about the Python-list
mailing list