[英]All combinations of a mapped list of lists in python
嗨,我如何獲取映射列表以打印所有可能的組合
說字典映射為= {1:[a,b],2:[c,d] ......
所以對於列表[1,2]和上面的示例映射,我想將a,d對c,d對的所有可能組合打印到列表中
看一下itertools模塊中的組合功能。
如果您正在尋找cd
與ab
所有配對,那么product函數應該可以幫助您:
>>> d = {1: ['a','b'], 2: ['c', 'd']}
>>> for t in product(*d.values()):
print t
('a', 'c')
('a', 'd')
('b', 'c')
('b', 'd')
如果您正在一次查看r的各種大小的所有abcd
組合,那么t 組合函數應該可以完成工作:
>>> for r in range(5):
for t in combinations('abcd', r):
print t
()
('a',)
('b',)
('c',)
('d',)
('a', 'b')
('a', 'c')
('a', 'd')
('b', 'c')
('b', 'd')
('c', 'd')
('a', 'b', 'c')
('a', 'b', 'd')
('a', 'c', 'd')
('b', 'c', 'd')
('a', 'b', 'c', 'd')
from itertools import product
mapping = {1:['a','b'], 2:['c','d']}
data = [1, 2]
for combo in product(*(mapping[d] for d in data)):
print combo
結果是
('a', 'c')
('a', 'd')
('b', 'c')
('b', 'd')
編輯它聽起來像您真正想要的是
strings = [''.join(combo) for combo in product(*(mapping[d] for d in data))]
給出strings == ['ac', 'ad', 'bc', 'bd']
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.