Мы можем сделать небольшой мод для кодирования из ОБЩИЙ СПИСОК НОМЕРОВ ИЗ ГИФЕНИРОВАННОЙ И КОМПАКТНОЙ СТРОКИ, КАК РАЗДЕЛИТЬ, КАК "1-5,25-30,4,5" (PYTHON RECIPE)
Преимущество этого подхода (сверх опубликованного) заключается в том, что его способность обрабатывать более сложные диапазоны с перекрытиями, такими как:
Для:
'2,3,4-8,2-5,9'
Производит
['2', '3', '4', '5', '6', '7', '8', '9']
В то время как принятое решение выдает
['2', ' 3', '4', '5', '6', '7', '8', '2', '3', '4', '5', ' 9']
С повторяющимися индексами
def hyphen_range(s):
""" Takes a range in form of "a-b" and generate a list of numbers between a and b inclusive.
Also accepts comma separated ranges like "a-b,c-d,f" will build a list which will include
Numbers from a to b, a to d and f"""
s= "".join(s.split())#removes white space
r= set()
for x in s.split(','):
t=x.split('-')
if len(t) not in [1,2]: raise SyntaxError("hash_range is given its arguement as "+s+" which seems not correctly formated.")
r.add(int(t[0])) if len(t)==1 else r.update(set(range(int(t[0]),int(t[1])+1)))
l=list(r)
l.sort()
return list(map(str, l)) # added string conversion
# Test shows handling of overlapping ranges and commas in pattern
# i.e. '2, 3, 4-8, 2-5, 9'
for x in ["6,7", "6-8", "10,12", "15-18", '6-8,10', '2, 3, 4-8, 2-5, 9']:
print(f"'{x}' -> {hyphen_range(x)}")
Выход
'6,7' -> ['6', '7']
'6-8' -> ['6', '7', '8']
'10,12' -> ['10', '12']
'15-18' -> ['15', '16', '17', '18']'6-8,10' -> ['6', '7', '8', '10']
'6-8,10' -> ['6', '7', '8', '10']
'2, 3, 4-8, 2-5, 9' -> ['2', '3', '4', '5', '6', '7', '8', '9']
Генератор Версия
def hyphen_range_generator(s):
""" yield each integer from a complex range string like "1-9,12, 15-20,23"
>>> list(hyphen_range('1-9,12, 15-20,23'))
[1, 2, 3, 4, 5, 6, 7, 8, 9, 12, 15, 16, 17, 18, 19, 20, 23]
>>> list(hyphen_range('1-9,12, 15-20,2-3-4'))
Traceback (most recent call last):
...
ValueError: format error in 2-3-4
"""
for x in s.split(','):
elem = x.split('-')
if len(elem) == 1: # a number
yield int(elem[0])
elif len(elem) == 2: # a range inclusive
start, end = map(int, elem)
for i in range(start, end+1):
yield str(i) # only mod to posted software
else: # more than one hyphen
raise ValueError('format error in %s' % x)
# Need to use list(...) to see output since using generator
for x in ["6,7", "6-8", "10,12", "15-18", '6-8,10', '2, 3, 4-8, 2-5, 9']:
print(f"'{x}' -> {list(hyphen_range_generator(x))}")
Выход
Same as the non-generator version above