parse string of integer sets with intervals to list

后端 未结 6 2048
南旧
南旧 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 am not aware of any built-in function that would do that. The following isn't particularly elegant, but gets the job done:

    s = "2,5,7-9,12"
    ret = []
    for tok in s.split(","):
      val = map(int, tok.split("-"))
      if len(val) == 1:
        ret += val
      else:
        ret += range(val[0], val[1] + 1)
    print ret
    

    One area where this solution may need work is the handling of negative numbers (it is not entirely clear from your question whether negative numbers can appear in the input).

提交回复
热议问题