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.
Like list(itertools.product(on,off)) but the results should use all four elements not only combination pairs like:
[(1.05, 5.53), (1.05, 3.12), (1.05, 3.75), (1.05, 4.75), (1.5, 5.53), (1.5, 3.12), (1.5, 3.75), (1.5, 4.75), (2.1, 5.53), (2.1, 3.12), (2.1, 3.75), (2.1, 4.75), (1.7, 5.53), (1.7, 3.12), (1.7, 3.75), (1.7, 4.75)]
So more like this:
off = [5.53,3.12,3.75,4.75]
on = [1.05,1.5,2.1,1.7]
# calculate combinations
x = combinations(on,off)
# Where...
# x[0] = off[0] * off[1] * off[2] * off[3] i.e
# x[0] = 5.53 * 3.12 * 3.75 * 4.75
#
# x[1] = off[0] * off[1] * off[2] * on[3] i.e
# x[1] = 5.53 * 3.12 * 3.75 * 1.7
#
# x[2] = off[0] * off[1] * on[2] * on[3] i.e
# x[2] = 5.53 * 3.12 * 2.1 * 1.7
#
# ...
#
# x[15] = on[0] * on[1] * on[2] * on[3] i.e
# x[15] = 1.05 * 1.5 * 2.1 * 1.7
The output can be similar to the itertools.product() method i.e [(5.53, 3.12, 3.75, 4.75),(5.53, 3.12, 3.75, 1.7), ...] I need to calculate the product but I’m interesting in the combination method.
Note: When I say pythonic way of doing this I mean a simple one or two lines taking advantage of pythons structures, libraries (itertools ect).
You can generate all
2**4possibilities by starting withitertools.product([0, 1], 4). This enumerates all possible sequences of0s and1s of length 4, and then you can translate each 0-1 sequence to a sequence of values fromoffandon, by takingoff[i]if the ith element of the 0-1 sequence is0, andon[i]otherwise. In code:To print the products instead of the lists:
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:
Combining with the earlier solutions gives: