[英]Combinations of two lists (not element-wise)
我有兩個清單:
a = ['a', 'b']
b = [1, 2, 3]
我想獲得列表的元素之間產生的組合b
和列表中的元素,但治療的元件a
作為對(或三元組等等,等等),如下這給示例len(b) ** len(a)
組合數量。
c = ["a_1 b_1", "a_1 b_2", "a_1 b_3", "a_2 b_1", "a_2 b_2", "a_2 b_3", "a_3 b_1", "a_3 b_2" "a_3 b_3"]
我曾嘗試使用itertools.product
(如描述在這里 ),但這將只給出6種可能的組合。
您可以使用itertools.product(..)
但指定repeat
為repeat=len(a)
。 所以你可以使用:
from itertools import product
def mul_product(a,b):
for tup in product(b,repeat=len(a)):
yield ' '.join('%s_%s'%t for t in zip(a,tup))
product(..)
將生成如下元組:
>>> list(product(b,repeat=len(a)))
[(1, 1), (1, 2), (1, 3), (2, 1), (2, 2), (2, 3), (3, 1), (3, 2), (3, 3)]
所以這里元組的第一個元素是附加到a_
元素,第二個元素附加到b_
。 現在我們zip(..)
他們連同a
清單,生產:
>>> list(map(lambda bi:list(zip(a,bi)),product(b,repeat=len(a))))
[[('a', 1), ('b', 1)], [('a', 1), ('b', 2)], [('a', 1), ('b', 3)], [('a', 2), ('b', 1)], [('a', 2), ('b', 2)], [('a', 2), ('b', 3)], [('a', 3), ('b', 1)], [('a', 3), ('b', 2)], [('a', 3), ('b', 3)]]
現在只需格式化( '%s_%s'%t
)和' '.join(..)
它們放在一起並yield
它們(或者你可以使用列表理解來生成列表)。
您的示例輸入的結果是:
>>> list(mul_product(a,b))
['a_1 b_1', 'a_1 b_2', 'a_1 b_3', 'a_2 b_1', 'a_2 b_2', 'a_2 b_3', 'a_3 b_1', 'a_3 b_2', 'a_3 b_3']
請注意,這里的元素是懶惰生成的。 如果您僅對前k
個感興趣,或者您不想一次生成所有這些內容,則此功能非常有用。
你可以通過明確創建您的配對項目itertools.product
,然后對那些與重新操作itertools.product
import itertools
a = ['a', 'b']
b = [1, 2, 3]
pairs = [list(itertools.product([ai], b)) for ai in a]
pairs
將包含可以再次輸入itertools.product
的兩個列表。
list(itertools.product(*pairs))
結果是:
[(('a', 1), ('b', 1)),
(('a', 1), ('b', 2)),
(('a', 1), ('b', 3)),
(('a', 2), ('b', 1)),
(('a', 2), ('b', 2)),
(('a', 2), ('b', 3)),
(('a', 3), ('b', 1)),
(('a', 3), ('b', 2)),
(('a', 3), ('b', 3))]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.