o = ['12-15', '40003', '40012', '71842-71844', '71848-71851','71853-54', '72717-72721', '72724-72732', '72734', '72787','68344', '46', '48', '49', '68351-68354', '68358', '59', ]def r(s):if'-'in s: a, b =map(int, s.split('-'))if b < a: sa, sb =map(str, (a, b)) la, lb =map(len, (sa, sb)) sb = sa[:la-lb] + sb b =int(sb)returnlist(range(a, b+1))else:return [int(s),]def r2(q): b = q.pop()whileTrue:try: a = b prev =None b = q.pop() prev = awhile (b == prev +1): prev = b b = q.pop()if prev and a!=prev:yield'-'.join(map(str, (a, prev)))else:yieldstr(a)exceptIndexError:if prev and a!=prev:yield'-'.join(map(str, (a, prev)))returnelse:yieldstr(a)returnz = []for x in o: z.extend(r(x))for i inrange(len(z) -1): a, b = z[i], z[i+1]if a>1000and b <1000: sa, sb =map(str, (a, b)) la, lb =map(len, (sa, sb)) sb = sa[:la-lb] + sb b =int(sb) z[i+1] = b# We have a full unwrapped list here (z)z1 =sorted(set(z))# Saved to z1z =sorted(set(z), reverse=True)z2 =list(r2(z))# So we have new folded list here (z2)