2016-03-08 73 views
0
source=[['a', 1], ['b', 1], ['d', 2], ['e', 2], ['f',3]] 
target=[list(x) for x in itertools.combinations(source,3)] 
for i in target: print(i) 

[['a', 1], ['b', 1], ['d', 2]] 
[['a', 1], ['b', 1], ['e', 2]] 
[['a', 1], ['b', 1], ['f', 3]] 
[['a', 1], ['d', 2], ['e', 2]] 
[['a', 1], ['d', 2], ['f', 3]] 
[['a', 1], ['e', 2], ['f', 3]] 
[['b', 1], ['d', 2], ['e', 2]] 
[['b', 1], ['d', 2], ['f', 3]] 
[['b', 1], ['e', 2], ['f', 3]] 
[['d', 2], ['e', 2], ['f', 3]] 

我可以通過嵌套序列元素重複itertools.combinations嗎?在這種情況下,元件[1]每個嵌套序列的產生:在基於嵌套序列元素的itertools.combinations中沒有重複?

[['a', 1], ['d', 2], ['f', 3]] 
[['a', 1], ['e', 2], ['f', 3]] 
[['b', 1], ['d', 2], ['f', 3]] 
[['b', 1], ['e', 2], ['f', 3]] 

回答

0

拆分出你輸入列表成單獨的基團代替,併產生他們的產品。你可以使用itertools.groupby()如果你的輸入由第二個參數排序:

from itertools import groupby, product 
from operator import itemgetter 

source = [['a', 1], ['b', 1], ['d', 2], ['e', 2], ['f', 3]] 
grouped = (list(group) for key, group in groupby(source, key=itemgetter(1))) 
for combo in product(*grouped): 
    print(list(combo)) 

如果輸入不被第二個參數排序,你會他們組通過使用詞典:

source = [['a', 1], ['b', 1], ['d', 2], ['e', 2], ['f', 3]] 
groups = {} 
for item in source: 
    groups.setdefault(item[1], []).append(item) 
grouped = [group for key, group in sorted(groups.items())] 

哪裏我假設你想對相同的第二個值進行排序以通知最終輸出訂單。

0

你可以寫一個生成器,過濾結果:

import itertools 

def my_combinations(*args, **kw): 
    for result in itertools.combinations(*args, **kw): 
     _,l = zip(*result) 
     if len(l) == len(set(l)): 
      yield result 

source=[['a', 1], ['b', 1], ['d', 2], ['e', 2], ['f',3]] 
target=[list(x) for x in my_combinations(source,3)] 
for i in target: print(i) 
+0

這裏的問題是,你過濾掉大部分元素,並且工作需要增加二次完成的工作量時,元素被添加到輸入。我的方法在O(N)時間內只產生所需的實際組合。 –

相關問題