我希望我能幫到你。檢查此(N = 3):
from itertools import product
from operators import mul
primes = [2,3,5]
n = 3
sets = product(*[[(i,j) for j in range(n)] for i in primes])
# Now 'sets' contains all the combinations you want. If you just wanted pow(i,j), write i**j instead and skip the map in the next enumeration
# list(sets)
#[((2, 0), (3, 0), (5, 0)),
# ((2, 0), (3, 0), (5, 1)),
# ((2, 0), (3, 0), (5, 2)),
# ... ... ...
# ((2, 2), (3, 2), (5, 0)),
# ((2, 2), (3, 2), (5, 1)),
# ((2, 2), (3, 2), (5, 2))]
productlist = []
for t in sets:
productlist.append(reduce(mul,map(lambda tp:tp[0]**tp[1],t)))
# now productlist contains the multiplication of each n(=3) items:
#[1, 5, 25, 3, 15, 75, 9, 45, 225, 2, 10, 50, 6, 30, 150, 18, 90, 450, 4, 20, 100, 12, 60, 300, 36, 180, 900]
# pow(2, 0) * pow(3, 0) * pow(5, 0) = 1
# pow(2, 0) * pow(3, 0) * pow(5, 1) = 5
# pow(2, 0) * pow(3, 0) * pow(5, 2) = 25
# .... ...
可替換地,一個襯裏可以是:
productlist = [reduce(mul,t) for t in product(*[[i**j for j in range(n)] for i in primes])]
http://docs.python.org/2/library/itertools.html#itertools.combinations會派上用場 – msw
是否必須按此順序? –