Python itertools - create only a subset of all possible products

I am working on a script that uses itertools to generate the desired combinations of given parameters. I am having trouble creating the appropriate "sets", however, when some variables are connected, i.e. Excluding certain combinations. Consider the following:

import itertools

A = ['a1','a2','a3']
B = ['b1','b2','b3']
C = ['c1','c2']

If I want to generate all possible combinations of these elements, I can simply use itertools.product ()

all_combinations = list(itertools.product(A,B,C))

What gives the expected

[('a1', 'b1', 'c1'), ('a1', 'b1', 'c2'), ('a1', 'b2', 'c1'), ... 
('a3', 'b2', 'c2'), ('a3', 'b3', 'c1'), ('a3', 'b3', 'c2')]

For 18 combinations (3 * 3 * 2)

However, how can I "bind" the parameters A and B so that each returned set contains only the elements "an", "bn"? That is, I tried:

ABprecombine = zip(A,B)
limited_combinations = list(itertools.product(ABprecombine,C))

What returns

[(('a1', 'b1'), 'c1'), (('a1', 'b1'), 'c2'), (('a2', 'b2'), 'c1'),
 (('a2', 'b2'), 'c2'), (('a3', 'b3'), 'c1'), (('a3', 'b3'), 'c2')]

(3 * 1 * 2) , , , - , , .

, , , "" , ?

+4
1

zping A B - . , :

limited_combinations = [(a, b, c) for ((a, b), c) in itertools.product(zip(A, B), C)]

, , , , NP- , . , .

+4

Source: https://habr.com/ru/post/1615087/


All Articles