Search code examples
pythonlisttostring

Is there a simple way to convert a list of integers to a formatted string in Python?


I am writing a program which generates a list of integers, for example:

[2, 5, 6, 7, 8, 9, 10, 15, 18, 19, 20]

This list can be very long, but it contains many consecutive values, as seen in this example.

In order to store it (in a database), I would like to convert it to a formatted string, in the following format:

"2,5-10,15,18-20"

I already have in mind a solution, which is iterating through the whole list to detect consecutive values and building the string.

My question is: is there another, simpler way of doing this conversion in Python?


Solution

  • Not exactly simple, but this produces the desired results:

    from itertools import groupby, count
    from operator import itemgetter
    
    a = [2, 5, 6, 7, 8, 9, 10, 15, 18, 19, 20]
    formatted = ','.join(str(x) if x == y else "{}-{}".format(x, y) for x, y in [itemgetter(0, -1)(list(g)) for k, g in groupby(a, lambda n, c = count(): n - next(c))])
    
    print(formatted)
    

    Which displays:

    2,5-10,15,18-20