【发布时间】:2016-12-02 18:19:57
【问题描述】:
假设我有一个类似的字符串:
a = "123**7*9"
我需要生成它的所有可能组合:
12300709...12399799
如何用 Python 做到这一点?
【问题讨论】:
-
字符串或整数作为输出?
标签: python combinations mask
假设我有一个类似的字符串:
a = "123**7*9"
我需要生成它的所有可能组合:
12300709...12399799
如何用 Python 做到这一点?
【问题讨论】:
标签: python combinations mask
您可以使用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))
【讨论】:
3星号
递归变体:
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
【讨论】: