Pythonic way to convert a list of integers into a string of comma-separated ranges

后端 未结 7 806
感情败类
感情败类 2020-12-01 05:06

I have a list of integers which I need to parse into a string of ranges.

For example:

 [0, 1, 2, 3] -> \"0-3\"
 [0, 1, 2, 4, 8] -> \"0-2,4,8\"
         


        
7条回答
  •  自闭症患者
    2020-12-01 05:29

    how about this mess...

    def rangefy(mylist):
        mylist, mystr, start = mylist + [None], "", 0
        for i, v in enumerate(mylist[:-1]):
                if mylist[i+1] != v + 1:
                        mystr += ["%d,"%v,"%d-%d,"%(start,v)][start!=v]
                        start = mylist[i+1]
        return mystr[:-1]
    

提交回复
热议问题