ようするに、この間の逆をやろうってことだ。
cf. 連続する数列をハイフンでまとめるPythonスクリプト – blog.panickblanket.com
import re
def expand_num(s):
a = re.split(", *", s)
r = re.compile("\d+-\d+")
def f(s1):
a, b = map(int, s1.split('-'))
return range(a, b+1)
def g(x):
if r.match(x):
return f(x)
else:
return [int(x)]
return reduce(lambda x, y: x + g(y), a, [])
if __name__ == '__main__':
print expand_num("1-3")
print expand_num("1-3, 5, 7-8")
print expand_num("1, 3-5, 7")
実行結果:
^o^ > python expand_num.py [1, 2, 3] [1, 2, 3, 5, 7, 8] [1, 3, 4, 5, 7]