为了得到myOutput字符串,操作myInput字符串的更快方法是什么?
myInput = "1,3-5,7"
myOutput = "1,3,4,5,7"发布于 2011-03-24 22:30:12
re.sub(
"(\d+)-(\d+)" ,
lambda x : ",".join( map( str , range( int(x.group(1)) , int( x.group(2) ) +1 ) )) ,
"1,3-5,7" )你可以得到"1,3,4,5,7“
发布于 2011-03-24 22:28:18
我记得上面的一个问题,把1,3,4,5,7变成了"1,3-5,7“,但我不记得是哪个了
这是相反的问题:
def expand(s):
return ','.join(sum([v if len(v)==1 else map(str, apply(lambda a,b: range(a,b+1), map(int, v))) for v in [p.split('-') for p in s.split(',')]],[]))
print expand("1,3-5,7")打印:
1,3,4,5,7发布于 2011-03-24 22:31:54
>>> def expand(s):
... for p in s.split(","):
... r = p.split("-")
... if len(r) == 1:
... yield str(r[0])
... else:
... for i in range(int(r[0]), int(r[1]) + 1):
... yield str(i)
...
>>> ",".join(expand("1,3-5,7"))
'1,3,4,5,7'
>>> ",".join(expand("1-5,8,10,13-19"))
'1,2,3,4,5,8,10,13,14,15,16,17,18,19'显然,如果输入不符合假设(字母、反向序列等),这将以各种有趣的方式失败,并且不适用于负数。
https://stackoverflow.com/questions/5420535
复制相似问题