Pregunta

Let's say I have lists as below:

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

I want to take pairs of foo (I know I can use iterools.combinations), but how do I have it so that when I take pairs of elements in foo, I take corresponding pairs in bar and baz?

E.g. When I pair 256 and 456 in foo, I pair 'a' and 'aa' in bar in the same order, and 2.9 and 2.7 in the same order in baz?

Also, when I take combinations, I should have no fear of (256, 456) and (456, 256) both being outputted since if we insert a list ordered as above, we should in fact get combinations and not more with permutations?

¿Fue útil?

Solución

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

Output:

(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)

Otros consejos

You could make combinations of indexes, and then use those index combinations to access the individual items:

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])

Here's a generic function for grouping combinations from any number of lists:

>>> 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'))]
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top