2016-09-22 70 views
-1

我從數據庫中獲取數據。從數據庫中他們在一個元組的形式:從元組創建組合

[('test1', 'test12', 'test13', 'test14'), 
('test21', 'test22', 'test23', 'test24'), 
('test31', 'test32', 'test33', 'test34'), 
('test41', 'test42', 'test43', 'test44'), 
('test51', 'test52', 'test53', 'test54'), 
('test61', 'test62', 'test63', 'test64'), 
('test71', 'test72', 'test73', 'test74'), 
('test81', 'test82', 'test83', 'test84'), 
('test91', 'test92', 'test93', 'test94'), 
('test11', 'test12', 'test13', 'test14')] 

而這正是我想要的: 使這些輸入的組合......所以輸出我有4個參數(如例子中)的組合和...

1)最重要的是,新的組合,值總是在它的位置,即如果在原始組合中的值是指數[1],這意味着在新的組合中,它應該也可以[1] ...

2)沒有重複的組合

作爲例子:

我得到的元組:

[('test91', 'test92', 'test93', 'test94'), 
('test11', 'test12', 'test13', 'test14')] 

而從這個我得到了新的組合:

[('test91', 'test12', 'test13', 'test14'), 
('test11', 'test92', 'test93', 'test94')] 

也許有可能使用做成對或其他方法。 幫助。

+0

所以你要的所有的組合元組,這會很多。 –

+0

是的,有很多可能的組合。 – Koushik

+0

暴力方法:使用四個嵌套循環來捕獲所有可能的組合。有n^4種可能的組合(n是4元組數組的行數) – jrook

回答

0

您需要使用內建包itertools中的product方法,該方法提供輸入迭代的笛卡爾乘積。

這裏是代碼,做你的願望。 但要小心,因爲巨大的列表會產生大量的組合,儘量不要用完內存。

from itertools import product 


data = [('test91', 'test92', 'test93', 'test94'), 
('test11', 'test12', 'test13', 'test14')] 

b = list(zip(*a)) # making list of n-th elements 
# b = [('test91', 'test11'), <- first elements 
# ('test92', 'test12'), <- second elements 
# ('test93', 'test13'), <- third elements 
# ('test94', 'test14')] 
variations = product(*b) 
output = set(variations) - set(a) # this is unique variations without input data 
# output = {('test11', 'test12', 'test13', 'test94'), 
# ('test11', 'test12', 'test93', 'test14'), 
# ('test11', 'test12', 'test93', 'test94'), 
# ('test11', 'test92', 'test13', 'test14'), 
# ('test11', 'test92', 'test13', 'test94'), 
# ('test11', 'test92', 'test93', 'test14'), 
# ('test11', 'test92', 'test93', 'test94'), 
# ('test91', 'test12', 'test13', 'test14'), 
# ('test91', 'test12', 'test13', 'test94'), 
# ('test91', 'test12', 'test93', 'test14'), 
# ('test91', 'test12', 'test93', 'test94'), 
# ('test91', 'test92', 'test13', 'test14'), 
# ('test91', 'test92', 'test13', 'test94'), 
# ('test91', 'test92', 'test93', 'test14')} 

如果你想輸出與輸入數據,你可以簡單地

output = set(variations) 

如果你需要一個列表,而不是設定,只是做

output = list(output)