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

2024-04-26 01:02:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图从字符串中的数字范围中得到一个列表。在Python3中如何做到这一点

我要转换以下字符串:

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

在此列表中:

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

Tags: 字符串列表数字python3
3条回答

您有一个列表,可以是int或range,
您可以分别迭代和处理它们

In [8]: series = []

In [9]: for token in "1-4, 6, 7-10".split(","):
   ...:     token = token.strip()
   ...:     if token.isnumeric():
   ...:         series.append(int(token))
   ...:     else:
   ...:         s, e = tuple(map(int, token.split("-")))
   ...:         # splits "4-6" and converts to int
   ...:         series.extend(list(range(s, e+1)))
   ...:

In [10]: series
Out[10]: [1, 2, 3, 4, 6, 7, 8, 9, 10]

像这样:

s = "3-12, 7, 1, 3-6"
d = []
for l in s.split(', '):
    if '-' in l:
        q = l.split('-')
        for n in range(int(q[0]),int(q[1])+1):
            d.append(n)
    else:
        d.append(int(l))
print(d)

输出:

[3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 7, 1, 3, 4, 5, 6]

您可以首先拆分','个字符。如果找到单个值,只需将其转换为int。如果找到破折号,请将其转换为整数范围

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]

相关问题 更多 >