I\'m trying to format a list of integers with Python and I\'m having a few difficulties achieving what I\'d like.
Input is a sorted list of Integers:
This seems a bit shorter than the current answers but is still pretty readable.
There might be a nicer way to do it without building an object up with an explicit loop, but I couldn't think of one.
L = [1, 2, 3, 6, 8, 9]
runs = [[str(L[0])]]
for first, second in zip(L, L[1:]):
if second == first + 1:
runs[-1].append(str(second))
else:
runs.append([str(second)])
result = ", ".join(["-".join(run) for run in runs])