2014-04-01 31 views
3

我有一些Python代碼一樣拼合結果從itertools.product

from itertools import product 
myItems = product(*groups.values()) 

這給了我itertools.product反對說,當我遍歷,看起來像

(myCustomObject,myCustomObject,myCustomObject(myCustomObject,myCustomObject,myCustomObject)) 

我怎麼能拉平此對象,它看起來像

(myCustomObject,myCustomObject,myCustomObject,myCustomObject,myCustomObject,myCustomObject) 

我想通過對象迭代,並沒有把它在一個列表中,因爲ŧ他myItems對象包含數十億記錄。什麼是最有效的方法來做到這一點?

+0

我不能說我明白你的例子。你能給出一個具體的例子來說明這個問題嗎? –

回答

4

itertools.product輸出是將產生的元組對象:

>>> list(itertools.product('ABCD', 'XYZ')) 
[('A', 'X'), ('A', 'Y'), ('A', 'Z'), ('B', 'X'), ('B', 'Y'), ('B', 'Z'), ('C', 'X'), ('C', 'Y'), ('C', 'Z'), ('D', 'X'), ('D', 'Y'), ('D', 'Z')] 

假設你只想扁平化所有product產生的元組,使用chain

>>> list(itertools.chain.from_iterable(itertools.product('ABCD', 'XYZ'))) 
['A', 'X', 'A', 'Y', 'A', 'Z', 'B', 'X', 'B', 'Y', 'B', 'Z', 'C', 'X', 'C', 'Y', 'C', 'Z', 'D', 'X', 'D', 'Y', 'D', 'Z'] 

如果飼餵對象到product本身是嵌套元組或列表,product不會遞歸地下降到它們中:

>>> list(itertools.product('ABCD', ['w', 'x',['y','z']])) 
[('A', 'w'), ('A', 'x'), ('A', ['y', 'z']), ('B', 'w'), ('B', 'x'), ('B', ['y', 'z']), ('C', 'w'), ('C', 'x'), ('C', ['y', 'z']), ('D', 'w'), ('D', 'x'), ('D', ['y', 'z'])] 

如果要拼合任意深度的名單,你需要做的是遞歸:

def flatten(container): 
    for i in container: 
     if isinstance(i, list) or isinstance(i, tuple): 
      for j in flatten(i): 
       yield j 
     else: 
      yield i 

>>> list(flatten(itertools.product('ABCD', ['w', 'x',['y','z']])))  
['A', 'w', 'A', 'x', 'A', 'y', 'z', 'B', 'w', 'B', 'x', 'B', 'y', 'z', 'C', 'w', 'C', 'x', 'C', 'y', 'z', 'D', 'w', 'D', 'x', 'D', 'y', 'z'] 

雖然我真的想不出一個用例爲具有不同深度的對象的嵌套列表首先給product ...