从Python中的字符串输入获取数值

从Python中的字符串输入获取数值,python,list,function,Python,List,Function,我需要创建一个函数,该函数以字符串作为输入,并输出所有数值的列表 一些例子: “22-28,31-35,37”应输出:[22,23,24,25,26,27,28,31,32,33,34,35,37] “22,24”应输出:[22,24] “23”应输出:[23] 我该怎么做 试试正则表达式 import re r = re.findall('[0-9]+-[0-9]+|[0-9]+',string) ans = [] for i in r: if '-' in i:

我需要创建一个函数,该函数以字符串作为输入,并输出所有数值的列表

一些例子:

  • “22-28,31-35,37”
    应输出:
    [22,23,24,25,26,27,28,31,32,33,34,35,37]
  • “22,24”
    应输出:
    [22,24]
  • “23”
    应输出:
    [23]

我该怎么做

试试正则表达式

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        

没有正则表达式:

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]