2016-09-20 56 views
0

Python itertools.product()以逗號分隔的1D列表並返回一個產品。我有許多的約數的列表的形式將列表轉換爲參數的元組

l=[[1, a1**1,a1**2,..a1**b1],[1,a2**1,..a2**b2],..[1, an**1, an**2,..an**bn]] 

當我將它傳遞給itertools.product()作爲參數我沒有得到期望的結果。我如何將這個整數列表提供給product()?

import itertools 

print([list(x) for x in itertools.product([1,2,4],[1,3])]) 
# [[1, 1], [1, 3], [2, 1], [2, 3], [4, 1], [4, 3]] #desired 

l1=[1,2,4],[1,3] #doesn't work 
print([list(x) for x in itertools.product(l1)]) 
#[[[1, 2, 4]], [[1, 3]]] 

l2=[[1,2,4],[1,3]] #doesn't work 
print([list(x) for x in itertools.product(l2)]) 
#[[[1, 2, 4]], [[1, 3]]] 
+0

請分享您的輸入所需的輸出,即'l2 = [[1,2,4],[1,3]' –

+0

另外,您想要兩個列表的笛卡爾積?因爲這就是'itertools.product()'的作用 –

+0

我想要一個n的所有因數列表,給出n的主要因子。 – sixtytrees

回答

3

您需要內product()*解開列表中使用*l2。在這種情況下,*[[1,2,4],[1,3]]的值將是[1,2,4],[1,3]。以下是您的代碼:

l2 = [[1,2,4],[1,3]] 
print([list(x) for x in itertools.product(*l2)]) 
# Output: [[1, 1], [1, 3], [2, 1], [2, 3], [4, 1], [4, 3]] 

請檢查:What does asterisk mean in python。另外閱讀有關*args**kwargs,您可能會發現它很有用。檢查:*args and **kwargs in python explained

+0

這個'*'是什麼?我想了解更多。像魅力一樣工作。 – sixtytrees

+1

選中此項:https://pythontips.com/2013/08/04/args-and-kwargs-in-python-explained/同時爲其他人尋找答案添加 –

+0

準確地說,您需要知道: http://stackoverflow.com/questions/400739/what-does-asterisk-mean-in-python –