How to convert numeric string ranges to a list in Python

后端 未结 6 1663
伪装坚强ぢ
伪装坚强ぢ 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:21

    This might be an overkill, but I just like pyparsing:

    from pyparsing import *
    
    def return_range(strg, loc, toks):
        if len(toks)==1:
            return int(toks[0])
        else:
            return range(int(toks[0]), int(toks[1])+1)
    def parsestring(s):
        expr = Forward()
        term = (Word(nums) + Optional(Literal('-').suppress() + Word(nums))).setParseAction(return_range)
        expr << term + Optional(Literal(',').suppress() + expr)
        return expr.parseString(s, parseAll=True)
    
    if __name__=='__main__':
        print parsestring('1,2,5-7,10')
    

提交回复
热议问题