parse string of integer sets with intervals to list

后端 未结 6 2052
南旧
南旧 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:06

    s = "2,5,7-9,12"
    result = list()
    
    for item in s.split(','):
        if '-' in item:
            x,y = item.split('-')
            result.extend(range(int(x), int(y)+1))
        else:
            result.append(int(item))
    
    print result
    

提交回复
热议问题