def cartesian_product(*lists): # lists can really be any sequences
if any([not l for l in lists]): # c.p. is empty if any list is empty
return
n = len(lists)
indexes = [0] * n
while True:
yield tuple(lists[i][indexes[i]] for i in xrange(n)) # currently indexed element of each list
# update indexes
for i in xrange(n-1, -1, -1): # loop through indexes from back
if indexes[i] < len(lists[i]) - 1: # stop at first index that can be incremented ...
indexes[i] += 1 # ... increment it ...
indexes[i+1:n] = [0] * (n - i - 1) # ... reset all succeeding indexes to 0
break
else: # no index could be incremented -> end
break
itertools.product
函数不需要您所说的“固定域”,也不需要任何函数。在例如,此代码执行您想要的操作:
对任何长度的序列都是一样的。在
itertools.product
已经得到了适当的建议,并且对于当前的问题工作得很好。如果您(如果只是出于学术原因)对示例实现感兴趣,下面是一个生成器函数:相关问题 更多 >
编程相关推荐