如何在python中同时进行组合? (itertools)

时间:2013-11-02 16:39:15

标签: python itertools

假设我的列表如下:

foo = [256, 456, 24, 79, 14]
bar = ['a', 'aa', 'dd', 'e', 'b']
baz = [2.9, 2.7, 1.9, 2.2, 1.1] 

我想接受foo对(我知道我可以使用iterools.combinations),但我如何拥有它以便当我在foo中使用成对元素时,我会在bar中使用相应的对{1}}和baz

E.g。当我在256中对456foo进行配对时,我会将'a''aa'按{1}}配对,并bar }和2.92.7中的顺序相同?

另外,当我采用组合时,我不应该担心baz(256, 456)都被输出,因为如果我们插入如上所述的列表,我们实际上应该得到组合而不是更多排列?

3 个答案:

答案 0 :(得分:1)

您可以组合索引,然后使用这些索引组合来访问各个项目:

indexes = list(range(len(foo)))
for i, j in itertools.combinations(indexes, 2):
     print(foo[i], foo[j])
     print(bar[i], bar[j])
     print(baz[i], baz[j])

答案 1 :(得分:1)

for c in itertools.combinations(zip(foo, bar, baz), 2):
    for u in zip(*c):
        print(u)

输出:

(256, 456)
('a', 'aa')
(2.9, 2.7)
(256, 24)
('a', 'dd')
(2.9, 1.9)
(256, 79)
('a', 'e')
(2.9, 2.2)
(256, 14)
('a', 'b')
(2.9, 1.1)
(456, 24)
('aa', 'dd')
(2.7, 1.9)
(456, 79)
('aa', 'e')
(2.7, 2.2)
(456, 14)
('aa', 'b')
(2.7, 1.1)
(24, 79)
('dd', 'e')
(1.9, 2.2)
(24, 14)
('dd', 'b')
(1.9, 1.1)
(79, 14)
('e', 'b')
(2.2, 1.1)

答案 2 :(得分:1)

这是一个通用函数,用于对来自任意数量列表的组合进行分组:

>>> def grouped_combos(n, *ls):
...     for comb in itertools.combinations(zip(*ls), n):
...         yield comb
>>> list(grouped_combos(2, [256, 456, 24, 79, 14], ['a', 'aa', 'dd', 'e', 'b']))
[((256, 'a'), (456, 'aa')), 
 ((256, 'a'), (24, 'dd')), 
 ((256, 'a'), (79, 'e')), 
 ((256, 'a'), (14, 'b')), 
 ((456, 'aa'), (24, 'dd')), 
 ((456, 'aa'), (79, 'e')), 
 ((456, 'aa'), (14, 'b')), 
 ((24, 'dd'), (79, 'e')), 
 ((24, 'dd'), (14, 'b')), 
 ((79, 'e'), (14, 'b'))]
>>> list(grouped_combos(4, [1, 2, 3, 4, 5], "abcde", "xyzzy"))
[((1, 'a', 'x'), (2, 'b', 'y'), (3, 'c', 'z'), (4, 'd', 'z')), 
 ((1, 'a', 'x'), (2, 'b', 'y'), (3, 'c', 'z'), (5, 'e', 'y')), 
 ((1, 'a', 'x'), (2, 'b', 'y'), (4, 'd', 'z'), (5, 'e', 'y')), 
 ((1, 'a', 'x'), (3, 'c', 'z'), (4, 'd', 'z'), (5, 'e', 'y')), 
 ((2, 'b', 'y'), (3, 'c', 'z'), (4, 'd', 'z'), (5, 'e', 'y'))]