Skip to content Skip to sidebar Skip to footer

Python Combinations Of 2 Lists

What is the pythonic way to calculated all the product combinations of two lists. So given two lists of length n I'd liked to return a list of length 2^n containing the products.

Solution 1:

You were very close, itertools.combinations().

Solution 2:

You can generate all 2**4 possibilities by starting with itertools.product([0, 1], 4). This enumerates all possible sequences of 0s and 1s of length 4, and then you can translate each 0-1 sequence to a sequence of values from off and on, by taking off[i] if the ith element of the 0-1 sequence is 0, and on[i] otherwise. In code:

>>>import itertools>>>off = [5.53,3.12,3.75,4.75]>>>on = [1.05,1.5,2.1,1.7]>>>for choices in itertools.product([0, 1], repeat=len(off)):...print [(on[i] if choice else off[i]) for i, choice inenumerate(choices)]... 
[5.53, 3.12, 3.75, 4.75]
[5.53, 3.12, 3.75, 1.7]
[5.53, 3.12, 2.1, 4.75]
[5.53, 3.12, 2.1, 1.7]
...<10 more entries omitted ...>
[1.05, 1.5, 2.1, 4.75]
[1.05, 1.5, 2.1, 1.7]

To print the products instead of the lists:

>>>import operator>>>for choices in itertools.product([0, 1], repeat=len(off)):...    elts = [(on[i] if choice else off[i]) for i, choice inenumerate(choices)]...print reduce(operator.mul, elts, 1)... 
307.32975
109.9917
172.10466
61.595352
...

If you have numpy available and are willing to work with numpy arrays instead of Python lists, then there are some nice tools like numpy.choose available. For example:

>>>import numpy>>>numpy.choose([0, 1, 0, 1], [off, on])
array([ 5.53,  1.5 ,  3.75,  1.7 ])
>>>numpy.product(numpy.choose([0, 1, 0, 1], [off, on]))
52.880624999999995

Combining with the earlier solutions gives:

>>>for c in itertools.product([0, 1], repeat=4):...print numpy.product(numpy.choose(c, [off, on]))... 
307.32975
109.9917
172.10466
61.595352
147.7546875
52.880625
...

Solution 3:

Is this what you want:

off = [5.53,3.12,3.75,4.75]
on = [1.05,1.5,2.1,1.7]
import itertools as it
import operator

indices = list(it.product([0,1],[0,1],[0,1],[0,1]))
off_on = off,on
a = [reduce(operator.mul,(off_on[z][i] for i,z in enumerate(x))) for x in indices]
print a


#Numpy solution
import numpy as np
indices = list(it.product([0,1],[0,1],[0,1],[0,1]))
off_on = off,on
b = np.array([off,on])
loff = range(len(off))
aa = [np.prod(b[list(x),loff]) for x in indices]

print aa
print aa == a

Post a Comment for "Python Combinations Of 2 Lists"