Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating all possible combinations from two arrays

I'm trying to think of an efficient way of solving the following problem:

Given any two arrays 'a' and 'b' I'd like to create all lists of combinations, each combination should contain tuples of one element from 'a' and one element from 'b'

for example:

a = ['p', 'q'], b = [True, False]

the output should be the following:

[{'p': False, 'q': False}, {'p': False, 'q': True}, {'p': True, 'q': 
False}, {'p': True, 'q': True}]
like image 344
crommy Avatar asked Nov 25 '25 02:11

crommy


1 Answers

Hey you can use itertools.product with repeat=2

Here is a working example which builds a list of dictionaries

[{k1:v1, k2:v2} for k1,v1,k2,v2 in itertools.product(a,b,repeat=2) if k1 != k2]
like image 130
megges Avatar answered Nov 27 '25 15:11

megges



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!