parse string of integer sets with intervals to list

后端 未结 6 2047
南旧
南旧 2021-02-09 13:47

I have \"2,5,7-9,12\" string.

I want to get [2, 5, 7, 8, 9, 12] list from it.

Is there any built-in function for it in python?

Thanks.

6条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-02-09 14:21

    I would define function:

    def make_range(s):
        out = []
        s = s.split(',')
        for n in s:
            if '-' in n:
                n = n.split('-')
                for i in range(int(n[0]), int(n[1]) + 1):
                    out.append(i)
            else:
                out.append(int(n))
        return out
    
    print make_range("2,5,7-9,12")
    #output [2, 5, 7, 8, 9, 12]
    

提交回复
热议问题