Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/319.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
计算所有产品组合的Pythonic方法_Python_Combinatorics - Fatal编程技术网

计算所有产品组合的Pythonic方法

计算所有产品组合的Pythonic方法,python,combinatorics,Python,Combinatorics,假设我有一个素数[2,3,5]的列表,我想得到所有N^3这样的乘积的列表(或迭代器): pow( 2, 0 ) * pow( 3, 0 ) * pow( 5, 0 ) pow( 2, 1 ) * pow( 3, 0 ) * pow( 5, 0 ) pow( 2, 0 ) * pow( 3, 1 ) * pow( 5, 0 ) pow( 2, 0 ) * pow( 3, 0 ) * pow( 5, 1 ) pow( 2, 1 ) * pow( 3, 1 ) * pow( 5, 0 ) p

假设我有一个素数[2,3,5]的列表,我想得到所有N^3这样的乘积的列表(或迭代器):

pow( 2, 0 ) * pow( 3, 0 ) * pow( 5, 0 ) 
pow( 2, 1 ) * pow( 3, 0 ) * pow( 5, 0 ) 
pow( 2, 0 ) * pow( 3, 1 ) * pow( 5, 0 ) 
pow( 2, 0 ) * pow( 3, 0 ) * pow( 5, 1 ) 
pow( 2, 1 ) * pow( 3, 1 ) * pow( 5, 0 ) 
pow( 2, 0 ) * pow( 3, 1 ) * pow( 5, 1 ) 
pow( 2, 1 ) * pow( 3, 0 ) * pow( 5, 1 ) 
[...]
pow( 2, N-1 ) * pow( 3, N-1 ) * pow( 5, N-1 ) 

蟒蛇式的方法是什么?(对于长度为L的列表)

我希望我的回答是对的。检查此项(N=3):

或者,一个衬里可以是:

productlist = [reduce(mul,t) for t in product(*[[i**j for j in range(n)] for i in primes])]
这应该做到:

from itertools import product
from operator import mul

def all_products(l, k):
    for t in product(*[[(p, e) for e in range(k)] for p in l]):
        yield reduce(mul, [x[0] ** x[1] for x in t], 1)
关键是使用

用法:

for prod in all_products([2, 3, 5], 3):
    print prod

这将为您提供所有形式为
2^a0*3^a1*5^a2
的产品,其中
0将得到处理它必须按此顺序排列吗?
for prod in all_products([2, 3, 5], 3):
    print prod