I'm trying to get a list from the range of numbers in a string. How I can do that in Python 3?
I want to convert the following string:
s = "1-4, 6, 7-10"
into this list:
l = [1, 2, 3, 4, 6, 7, 8, 9, 10]
I'm trying to get a list from the range of numbers in a string. How I can do that in Python 3?
I want to convert the following string:
s = "1-4, 6, 7-10"
into this list:
l = [1, 2, 3, 4, 6, 7, 8, 9, 10]
You could first split on ','
characters. If you find a single value, just convert to int
. If you find a dash, convert to a range of integers.
def listify(s):
output = []
for i in s.split(','):
if '-' in i:
start, stop = [int(j) for j in i.split('-')]
output += list(range(start, stop+1))
else:
output.append(int(i))
return output
>>> listify("1-4, 6, 7-10")
[1, 2, 3, 4, 6, 7, 8, 9, 10]
You have a list which can either have an int or a range,
you can iterate and handle them separately
In [8]: series = []
In [9]: for token in "1-4, 6, 7-10".split(","):
...: token = token.strip()
...: if token.isnumeric():
...: series.append(int(token))
...: else:
...: s, e = tuple(map(int, token.split("-")))
...: # splits "4-6" and converts to int
...: series.extend(list(range(s, e+1)))
...:
In [10]: series
Out[10]: [1, 2, 3, 4, 6, 7, 8, 9, 10]
Like this:
s = "3-12, 7, 1, 3-6"
d = []
for l in s.split(', '):
if '-' in l:
q = l.split('-')
for n in range(int(q[0]),int(q[1])+1):
d.append(n)
else:
d.append(int(l))
print(d)
Output:
[3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 7, 1, 3, 4, 5, 6]
If you happen to be really motivated to do this as compactly as possible, it can be done as a nested comprehension:
>>> [i
... for r in (list(map(int, q.split("-")))
... for q in s.split(", ")
... ) for i in range(r[0], r[-1]+1)
... ]
[1, 2, 3, 4, 6, 7, 8, 9, 10]
Here it is built up step by step:
>>> s.split(", ")
['1-4', '6', '7-10']
>>> [q.split("-") for q in s.split(", ")]
[['1', '4'], ['6'], ['7', '10']]
>>> [list(map(int, q.split("-")))
... for q in s.split(", ")
... ]
[[1, 4], [6], [7, 10]]
>>>
>>> [range(r[0], r[-1]+1)
... for r in (list(map(int, q.split("-")))
... for q in s.split(", "))
... ]
[range(1, 5), range(6, 7), range(7, 11)]
>>>
>>> [i
... for r in (list(map(int, q.split("-")))
... for q in s.split(", ")
... ) for i in range(r[0], r[-1]+1)
... ]
[1, 2, 3, 4, 6, 7, 8, 9, 10]