Formatting consecutive numbers

后端 未结 5 2005
轻奢々
轻奢々 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:52

    Since the other guy who posted this solution deleted his answer...

    Here's a O(n) string building solution:

    def stringify(lst):
        result = str(lst[0])
        end = None
        for index, num in enumerate(lst[1:]):
            if num - 1 == lst[index]:  # the slice shifts the index by 1 for us
                end = str(num)
            else:
                if end:
                    result += '-' + end
                    end = None
                result += ', ' + str(num)
        # Catch the last term
        if end:
            result += '-' + str(num)
        return result
    

    See the repl.it

提交回复
热议问题