Formatting consecutive numbers

后端 未结 5 2004
轻奢々
轻奢々 2021-01-18 15:00

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:



        
5条回答
  •  抹茶落季
    2021-01-18 15:34

    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])
    

提交回复
热议问题