2011-06-27 26 views
16

我想要的東西,像下面的代碼,但「Python的」風格或使用標準庫:的Python的方式來產生對

def combinations(a,b): 
    for i in a: 
     for j in b: 
      yield(i,j) 
+0

你能否提供一些樣品的輸入和輸出的?目前,您正在爲'a'和'b'中的每個元素創建一對。這真的是你想要的嗎? –

回答

26

這些都不是真正的在組合的意義上的「組合」,這是相當元素來自ab的笛卡爾積。在標準庫來生成這些雙功能是itertools.product()

for i, j in itertools.product(a, b): 
    # whatever 
7

itertools庫有組合數學函數。像斯文說,itertools.product會在這種情況下,相應的功能:

list(itertools.product('ab', 'cd')) 
[('a', 'c'), ('a', 'd'), ('b', 'c'), ('b', 'd')] 
7

嵌套生成器表達式也可以工作:

product = ((i, j) for i in a for j in b) 
for i, j in product: 
    # ... 
+0

不是標準的庫函數,但方式更pythonic然後我的「C」類版本;-)感謝您提供替代itertools.product() – Dima

+1

@DIMI:至少你使用'yield';) – mhyfritz

3
>>>a=[1,2,3] 
>>>b=[4,5,6] 
>>>zip(a,b) 
[(1, 4), (2, 5), (3, 6)] 
+0

我也想(1 ,5),(1,6),(2,4),(2,6),(3,4),(3,5)除了由拉鍊創建的三對.... – Dima

+1

雖然@ fransua得到-2 downvote,這正是我需要的一對。我會upvote你的答案。 – shailenTJ

9

正如@Sven說,你的代碼試圖獲得列表ab的所有有序元素對。在這種情況下,itertools.product(a,b)是你想要的。如果您確實想要「組合」,這些組合是列表a的所有無序對的不同元素,那麼您需要itertools.combinations(a,2)

>>> for pair in itertools.combinations([1,2,3,4],2): 
... print pair 
... 
(1, 2) 
(1, 3) 
(1, 4) 
(2, 3) 
(2, 4) 
(3, 4) 
1

Create建立對(偶,奇)組合

>>> a = { (i,j) for i in range(0,10,2) for j in range(1,10,2)} 
>>> a 
{(4, 7), (6, 9), (0, 7), (2, 1), (8, 9), (0, 3), (2, 5), (8, 5), (4, 9), (6, 7), (2, 9), (8, 1), (6, 3), (4, 1), (4, 5), (0, 5), (2, 3), (8, 7), (6, 5), (0, 1), (2, 7), (8, 3), (6, 1), (4, 3), (0, 9)} 

def combinations(lista, listb): 
    return { (i,j) for i in lista for j in listb } 

>>> combinations([1,3,5,6],[11,21,133,134,443]) 
{(1, 21), (5, 133), (5, 11), (5, 134), (6, 11), (6, 134), (1, 443), (3, 11), (6, 21), (3, 21), (1, 133), (1, 134), (5, 21), (3, 134), (5, 443), (6, 443), (1, 11), (3, 443), (6, 133), (3, 133)} 
相關問題