假设我有一个字符串,例如:
a = "123**7*9"
我需要生成它的所有可能组合:
12300709...12399799
如何用 Python 做到这一点?
假设我有一个字符串,例如:
a = "123**7*9"
我需要生成它的所有可能组合:
12300709...12399799
如何用 Python 做到这一点?
您可以使用itertools.product
和字符串格式:
>>> from itertools import product
>>> strs = "123**7*9"
>>> c = strs.count("*") #count the number of "*"'s
>>> strs = strs.replace("*","{}") #replace '*'s with '{}' for formatting
>>> for x in product("0123456789",repeat=c):
... print strs.format(*x) #use `int()` to get an integer
12300709
12300719
12300729
12300739
12300749
12300759
12300769
12300779
12300789
12300799
....
您也可以只使用标准库这样做:
a = "123**7*9"
a = a.replace("*", "%d")
for x in range(10):
for y in range(10):
for z in range(10):
print a % (x,y,z)
编辑,繁荣:
a = "123**7*9"
c = a.count("*")
a = a.replace("*", "%s")
for x in range(10**c):
print a % tuple(list("%03d" % x))
递归变体:
def combinate(pattern, order=0):
if pattern:
for val in combinate(pattern[:-1], order+1):
last_value = pattern[-1]
if last_value == '*':
for gen in xrange(10):
value = gen * (10**order) + val
yield value
else:
value = int(last_value)*(10**order)+val
yield value
else:
yield 0
for i in combinate('1*1**2'):
print i