-3
我有一个像123[4-6][1-2]
一个字符串,我想一个函数,给了我清单,所有的组合:Python字符串分割组合
['12341', '12342', '12351', '12352', '12361', '12362']
输入字符串可以像[12-45]888[1-2]76[0-9]
一个价值,我想在功能Python给我所有组合的列表。
我有一个像123[4-6][1-2]
一个字符串,我想一个函数,给了我清单,所有的组合:Python字符串分割组合
['12341', '12342', '12351', '12352', '12361', '12362']
输入字符串可以像[12-45]888[1-2]76[0-9]
一个价值,我想在功能Python给我所有组合的列表。
使用正则表达式找到范围和itertools.product
找到所有可能性。
import re
from itertools import product
def getranges(s):
for a, b in re.findall(r"\[(\d+)-(\d+)\]", s):
yield range(int(a), int(b)+1)
def strcombs(s):
for r in product(*getranges(s)):
it = iter(str(i) for i in r)
yield re.sub(r"\[\d+-\d+\]", lambda _: next(it), s)
s = "123[4-6][1-2]"
print(list(strcombs(s))) # ['12341', '12342', '12351', '12352', '12361', '12362']
你试过了吗? – Woot4Moo
@ Woot4Moo ...张贴在这里。 – Leb
@Leb har har,我正在寻找一个代码片段,试图尝试并且无法正常工作。 – Woot4Moo