我需要创建一个函数,它将一个字符串作为输入并输出所有数值的列表。
一些例子:
"22-28, 31-35, 37"
应输出:[22, 23, 24, 25, 26, 27, 28, 31, 32, 33, 34, 35, 37]
"22, 24"
应输出:[22, 24]
"23"
应输出:[23]
我该怎么做?
答案 0 :(得分:2)
尝试正则表达式。
import re
r = re.findall('[0-9]+-[0-9]+|[0-9]+',string)
ans = []
for i in r:
if '-' in i:
t = i.split('-')
ans.extend(range(int(t[0]),int(t[1])))
else:
ans.append(int(i))
print ans
答案 1 :(得分:1)
没有正则表达式:
def text_range(s):
res = []
for pc in s.split(','):
if '-' in pc: # this assumes no negative numbers in the list!
a,b = [int(i) for i in pc.split('-')]
res.extend(range(a, b+1))
else:
res.append(int(pc))
return res
然后
text_range("22-28, 31-35, 37") # -> [22, 23, 24, 25, 26, 27, 28, 31, 32, 33, 34, 35, 37]