Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Expand a range which looks like: "1-3,6,8-10" to [1,2,3, 6, 8,9,10]

Tags:

python

I am trying to add an option to my program which allow the user to choose which steps of the program he wants to do.

I would like to be able to parse a string like "1-3,6,8-10" and get [1, 2, 3, 6, 8, 9, 10].

Do you know if something in Python which is doing that already exists ?

like image 655
taktak004 Avatar asked Sep 12 '13 08:09

taktak004


People also ask

How do you extend range in Python?

To convert a Python Range to Python List, use list() constructor, with range object passed as argument. list() constructor returns a list generated using the range. Or you can use a for loop to append each item of range to list.


2 Answers

This function does what you asked. It assumes no negative numbers are used, otherwise it needs some changes to support that case.

def mixrange(s):
    r = []
    for i in s.split(','):
        if '-' not in i:
            r.append(int(i))
        else:
            l,h = map(int, i.split('-'))
            r+= range(l,h+1)
    return r


print mixrange('1-3,6,8-10')
like image 80
LtWorf Avatar answered Oct 16 '22 05:10

LtWorf


One way using list comprehensions:

s = "1-3,6,8-10"
x = [ss.split('-') for ss in s.split(',')]
x = [range(int(i[0]),int(i[1])+1) if len(i) == 2 else i for i in x]
print([int(item) for sublist in x for item in sublist])

Outputs:

[1, 2, 3, 6, 8, 9, 10]
like image 34
Chris Seymour Avatar answered Oct 16 '22 05:10

Chris Seymour