How to convert numeric string ranges to a list in Python

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

    Very short, and elegant (imho):

    >>> txt = "1,2,5-7,10"
    >>> # construct list of xranges
    >>> xranges = [(lambda l: xrange(l[0], l[-1]+1))(map(int, r.split('-'))) for r in txt.split(',')]
    >>> # flatten list of xranges
    >>> [y for x in xranges for y in x]
    [1, 2, 5, 6, 7, 10]
    

提交回复
热议问题