You can use a nested list comprehension, checking whether the current part contains a -
and using either a range
or creating a one-elemented list accordingly:
>>> s = "1-10, 20, 30, 40, 400-410"
>>> [n for part in s.split(", ") for n in (range(*map(int, part.split("-"))) if "-" in part else [int(part)])]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 20, 30, 40, 400, 401, 402, 403, 404, 405, 406, 407, 408, 409]
Maybe split this up, for readability:
>>> to_list = lambda part: range(*map(int, part.split("-"))) if "-" in part else [int(part)]
>>> [n for part in s.split(", ") for n in to_list(part)]
Note: As in your first example, this will translate "1-10"
to [1, 2, ..., 9]
, without 10
.
As noted in comments, this will not work for negative numbers, though, trying to split -3
or -4--2
into pairs of numbers. For this, you could use regular expressions...
>>> def to_list(part):
... m =re.findall(r"(-?\d+)-(-?\d+)", part)
... return range(*map(int, m[0])) if m else [int(part)]
...
>>> s = "-10--5, -4, -2-3"
>>> [n for part in s.split(", ") for n in to_list(part)]
[-10, -9, -8, -7, -6, -4, -2, -1, 0, 1, 2]
... or just use a different delimiter for ranges, e.g. -10:-5
.