How to convert numeric string ranges to a list in Python

后端 未结 6 1669
伪装坚强ぢ
伪装坚强ぢ 2020-12-08 07:44

I would like to be able to convert a string such as \"1,2,5-7,10\" to a python list such as [1,2,5,6,7,10]. I looked around and found this, but I was wondering if there is a

6条回答
  •  无人及你
    2020-12-08 08:13

    Ugh, the answers are so verbose! Here is a short and elegant answer:

    def rangeString(commaString):
        def hyphenRange(hyphenString):
            x = [int(x) for x in hyphenString.split('-')]
            return range(x[0], x[-1]+1)
        return chain(*[hyphenRange(r) for r in commaString.split(',')])
    

    Demo:

    >>> list( f('1,2,5-7,10') )
    [1, 2, 5, 6, 7, 10]
    

    Easily modifiable to handle negative numbers or return a list. Also will need from itertools import chain, but you can substitute sum(...,[]) for it if you are not working with range objects (or sum(map(list,iters),[])) and you don't care about being lazy.

提交回复
热议问题