Conversion of a string with both individual numbers and ranges of numbers to the list of integer values can be made as follows:
For example a line:
1 |
src = '1, 3-5, 8' |
Split the line by comma delimiter:
1 |
linearr = [s.strip() for s in re.split(r'[,;]+| ,', src) if s] |
Let’s split the resulting list into two lists. In the first list, we put only the individual values. In the second – the values got from the ranges of numbers.
1 2 |
linearrframes = [int(i) for i in linearr if '-' not in i] linearrdiapasones = sum([list(range(int(i.split('-')[0]), int(i.split('-')[1]) + 1)) for i in linearr if '-' in i], []) |
Combine the lists into one and drop the duplicate values.
1 2 |
linearrframes.extend(linearrdiapasones) print(list(set(linearrframes))) |
Complete code:
1 2 3 4 5 6 7 8 9 |
src = '1, 3-5, 8' print(src) linearr = [s.strip() for s in re.split(r'[,;]+| ,', src) if s] linearrframes = [int(i) for i in linearr if '-' not in i] linearrdiapasones = sum([list(range(int(i.split('-')[0]), int(i.split('-')[1]) + 1)) for i in linearr if '-' in i], []) linearrframes.extend(linearrdiapasones) print(list(set(linearrframes))) # '1, 3-5, 8' # [1, 3, 4, 5, 8] |