[英]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.