Python3 正则表达式转义函数



所以我得到了一串长度可变的数字,我需要使用该字符串中的数字找到所有可能的数字组合,其中只有中间的数字可以更改,例如:

如果我得到 123,

我需要找到 1x2y3 的组合,其中 x、y 是任何数字

如果我得到 5312

,我需要找到 5a3b1c2 的组合,其中 a、b、c 是任何数字

我认为使用 python 的 re.escape 函数可以实现这一点,这就是我所到的:

#Given the digits '123' from STDIN
#create a string "1d2d3"
my_regex_string = 'd'.join(input().split())
#Set x as starting point, set y as limit (not the most efficient)
x = 10**(len(my_regex_string)-1) * int(my_regex_string[0])
y = 10**(len(my_regex_string)-1) * (int(my_regex_string[0]) + 1)
while x < y:
    if bool(re.match(re.escape(p), str(x)))
        print(x)
    x+=1

我需要反馈,我的方法有意义吗?此任务是否可以使用正则表达式完成,还是我需要另一种方法?

我认为

,就像wolfrevokcats所说的那样,pythonic这样做的方式是使用itertools.product函数。像这样的代码:

from itertools import product
s = input()
r = "{}".join(list(s))
c = [int(r.format(*f)) for f in product(range(0,10), repeat=len(s)-1)]

这是一个使用迭代工具的解决方案,可能不是最复杂的,但它有效:

>>> import itertools
>>> x = map(lambda z: [s[i] + str(z[i]) for i in range(len(s)-1)] + [s[-1]], list(itertools.product(range(10), repeat=len(s)-1)))
>>> y = map(lambda z: "".join(z), x)
>>> list(y)

最新更新