Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

parse string of integer sets with intervals to list

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.

UPD. I suppose, the straight answer is No. Anyway, thanks for your "snippets". Using one, suggested by Sven Marnach.

like image 843
disfated Avatar asked Apr 18 '11 15:04

disfated


2 Answers

s = "2,5,7-9,12"
ranges = (x.split("-") for x in s.split(","))
print [i for r in ranges for i in range(int(r[0]), int(r[-1]) + 1)]

prints

[2, 5, 7, 8, 9, 12]
like image 182
Sven Marnach Avatar answered Oct 21 '22 04:10

Sven Marnach


s = "2,5,7-9,12"
result = list()

for item in s.split(','):
    if '-' in item:
        x,y = item.split('-')
        result.extend(range(int(x), int(y)+1))
    else:
        result.append(int(item))

print result
like image 45
Andreas Jung Avatar answered Oct 21 '22 04:10

Andreas Jung