从具有数字范围的字符串中获取数字列表

问题描述:

我正在尝试从字符串中的数字范围获取列表.如何在Python 3中做到这一点?

I'm trying to get a list from the range of numbers in a string. How I can do that in Python 3?

我要转换以下字符串:

s = "1-4, 6, 7-10"

进入此列表:

l = [1, 2, 3, 4, 6, 7, 8, 9, 10]

您可以先分割为','个字符.如果找到单个值,则只需转换为int.如果找到破折号,请转换为整数范围.

You could first split on ',' characters. If you find a single value, just convert to int. If you find a dash, convert to a range of integers.

def listify(s):
    output = []
    for i in s.split(','):
        if '-' in i:
            start, stop = [int(j) for j in i.split('-')]
            output += list(range(start, stop+1))
        else:
            output.append(int(i))
    return output

>>> listify("1-4, 6, 7-10")
[1, 2, 3, 4, 6, 7, 8, 9, 10]