生成包含字符串和数字的范围

时间:2019-04-22 18:00:17

标签: python-3.x

我正在尝试在两个变量之间创建一个范围。变量包含字符串和数字字符。

例如P9160-P9163或P360-P369。 P不是常数,可以是任何字符/多个,但是我正在尝试生成一个列表,其中将包含之间的所有值。

我尝试查看ASCII字符,但对我不起作用。

有什么想法吗?

x = 'P9160'
y = 'P9163'

x = re.match(r"([a-z]+)([0-9]+)", x, re.I)
y = re.match(r"([a-z]+)([0-9]+)", y, re.I)

for i in range(int(x.groups()[1]), int(y.groups()[1])+1):
    print("{}{}".format(x.groups()[0], i))

1 个答案:

答案 0 :(得分:0)

使用可重用的正则表达式模式和生成器表达式确实可以提高代码性能。

import re

x = 'P9160'
y = 'P9173'

# resuable regex pattern
regex = re.compile(r"([a-zA-Z]+)(\d+)")

x, y = regex.match(x), regex.match(y)

# generator expression
xy = (x.groups()[0]+str(i) for i in range(int(x.groups()[1]), int(y.groups()[1])+1))

# list of all values from the generator
print(list(xy))