I have a list of integers which I need to parse into a string of ranges.
For example:
[0, 1, 2, 3] -> \"0-3\"
[0, 1, 2, 4, 8] -> \"0-2,4,8\"
Whether this is pythonic is up for debate. But it is very compact. The real meat is in the Rangify()
function. There's still room for improvement if you want efficiency or Pythonism.
def CreateRangeString(zones):
#assuming sorted and distinct
deltas = [a-b for a, b in zip(zones[1:], zones[:-1])]
deltas.append(-1)
def Rangify((b, p), (z, d)):
if p is not None:
if d == 1: return (b, p)
b.append('%d-%d'%(p,z))
return (b, None)
else:
if d == 1: return (b, z)
b.append(str(z))
return (b, None)
return ','.join(reduce(Rangify, zip(zones, deltas), ([], None))[0])
To describe the parameters:
deltas
is the distance to the next value (inspired from an answer here on SO)Rangify()
does the reduction on these parameters
b
- base or accumulatorp
- previous start rangez
- zone numberd
- delta