Formatting consecutive numbers

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

    list=[1, 2, 3, 4, 6, 10, 11, 12, 13]
    y=str(list[0])
    
    for i in range(0, len(list)-1):
        if list[i+1] == list[i]+1 :
            y+= '-' + str(list[i + 1])
        else:
            y+= ',' + str(list[i + 1])
    print y
    
    
    z= y.split(',')
    outputString= ''
    for i in z:
        p=i.split('-')
        if p[0] == p[len(p)-1]:
            outputString = outputString + str(p[0]) + str(',')
        else:
            outputString = outputString + str(p[0]) + str('-') + str(p[len(p) - 1]) + str(',')
    
    outputString = outputString[:len(outputString) - 1]
    print 'final ans: ',outputString
    

    add these lines after your code.

提交回复
热议问题