Iterate Over All Combinations of Values in Multiple Lists in Python

Iterate over all combinations of values in multiple lists in Python

itertools.product should do the trick.

>>> import itertools
>>> list(itertools.product([1, 5, 8], [0.5, 4]))
[(1, 0.5), (1, 4), (5, 0.5), (5, 4), (8, 0.5), (8, 4)]

Note that itertools.product returns an iterator, so you don't need to convert it into a list if you are only going to iterate over it once.

eg.

for x in itertools.product([1, 5, 8], [0.5, 4]):
# do stuff

Iterate over combinations of items of multiple lists in Python

You could use itertools.product to make all possible combinations from your lists. The result will be one long list of tuple with an element from each list in the order you passed the list in.

>>> a = [1,2,3]
>>> b = ['a', 'b', 'c']
>>> c = [4,5,6]
>>> import itertools

>>> list(itertools.product(a,b,c))
[(1, 'a', 4), (1, 'a', 5), (1, 'a', 6), (1, 'b', 4), (1, 'b', 5), (1, 'b', 6), (1, 'c', 4), (1, 'c', 5), (1, 'c', 6),
(2, 'a', 4), (2, 'a', 5), (2, 'a', 6), (2, 'b', 4), (2, 'b', 5), (2, 'b', 6), (2, 'c', 4), (2, 'c', 5), (2, 'c', 6),
(3, 'a', 4), (3, 'a', 5), (3, 'a', 6), (3, 'b', 4), (3, 'b', 5), (3, 'b', 6), (3, 'c', 4), (3, 'c', 5), (3, 'c', 6)]

For example

for ai, bi, ci in itertools.product(a,b,c):
print ai, bi, ci

Output

1 a 4
1 a 5
1 a 6
... etc

All combinations of a list of lists

you need itertools.product:

>>> import itertools
>>> a = [[1,2,3],[4,5,6],[7,8,9,10]]
>>> list(itertools.product(*a))
[(1, 4, 7), (1, 4, 8), (1, 4, 9), (1, 4, 10), (1, 5, 7), (1, 5, 8), (1, 5, 9), (1, 5, 10), (1, 6, 7), (1, 6, 8), (1, 6, 9), (1, 6, 10), (2, 4, 7), (2, 4, 8), (2, 4, 9), (2, 4, 10), (2, 5, 7), (2, 5, 8), (2, 5, 9), (2, 5, 10), (2, 6, 7), (2, 6, 8), (2, 6, 9), (2, 6, 10), (3, 4, 7), (3, 4, 8), (3, 4, 9), (3, 4, 10), (3, 5, 7), (3, 5, 8), (3, 5, 9), (3, 5, 10), (3, 6, 7), (3, 6, 8), (3, 6, 9), (3, 6, 10)]

Python - Loop over all instances of multiple lists

You can use itertools.product like so:

list1 = [1,2,3,4]
list2 = [6,7,8]
find_this_value = (1, 8)

found_value = False
for permutation in itertools.product(list1, list2):
if permutation == find_this_value:
found_value = True
break

if found_value:
pass # Take action

itertools.product returns a generator with all of the possible permutations of the 2 lists. Then, you simply iterate over those, and search until you find the value you want.

Calculation involving iterations over all combinations of values in two lists in Python

So I think the issue is that you are having trouble conceptualizing the grid that these solutions are supposed to be stored in. This calculation is good because it is an introduction to certain optimizations and additionally there are a few ways to do it. I'll show you the three I threw together.

First, you could do it with lists and loops, which is very inefficient (numpy is just to show the shape):

import numpy as np
x, y = [], []
length = 35
for i in range(length+1):
x.append(i/length) # Normalizing over the range of the grid
y.append(i/length) # to compare to later example

def func(x, y, a, b):
return ((y-x)*(a/b))+x

a=b=1 # Set a value for a and b

row = []
for i in x:
column = []
for j in y:
column.append(func(i,j,a,b))
row.append(column)

print(row)
print(np.shape(row))

This will output a solution assuming a and b are known, and it is a 36x36 matrix. To make the matrix, we have to create a large memory space which I called row and smaller memory spaces that are recreated each iteration of the loop I called column. The inner-most loop appends the values to the column list, while the evaluated column lists are appended to the top level row list. It will then have a matrix-esque appearance even if it is just a list of lists.

A more efficient way to do this is to use numpy. First, we can keep the loops if you wish and do the calculation with numpy arrays:

import numpy as np

x = y = np.linspace(0,1,36)
result = np.zeros((len(x), len(y)))

F = lambda x,y,a,b: ((y-x)*(a/b))+x

a=b=1

for idx, i in enumerate(x):
for jdx, j in enumerate(y):
result[idx, jdx] = F(i,j,a,b) # plug in value at idx, jdx grip point

print(result)
print(result.shape)

So here we create the grid using linspace and I just chose values from 0 to 1 in 36 steps. After this, I create the grid we will store the solutions in by making a numpy array with dimensions given by the length of the x and y arrays. Finally The function is created with a lambda function, which serves the same purpose of the def previously, just in one line. The loop is kept for now, which iterates over the values i, j and indexes of each idx, jdx. The results are added into the allocated storage at each index with result[idx, jdx] = F(i,j,a,b).

We can do better, because numpy exists to help remove loops in calculations. Instead, we can utilize the meshgrid function to create a matrix and evaluate the function with it, as so:

import numpy as np

x = y = np.linspace(0,1,36)
X, Y = np.meshgrid(x,y)

F = lambda x,y,a,b: ((y-x)*(a/b))+x

a=b=1

result = F(X,Y,a,b) # Plug in grid directly

print(result.T)
print(result.shape)

Here we use the numpy arrays and tell meshgrid that we want a 36x36 array with these values at each grid point. Then we define the lambda function as before and pass the new X and Y to the function. The output does not require additional storage or loops, so then we get the result.

It is good to practice using numpy for any calculation you want to do, because they can usually be done without loops.

Combinations of multiple lists

As an alternative to regenerating the list of combinations, compute the product of the combinations up front; this also saves you from nesting for loops.

from itertools import combinations, product

list1 = list("abcdefgh")
list2 = list("ijk")
list3 = list("lmnop")

l1 = combinations(list1, 5)
l2 = combinations(list2, 2)
l3 = combinations(list3, 3)
for c1, c2, c3 in product(l1, l2, l3):
sample = c1 + c2 + c3
print(sample)

How do I iterate through combinations of a list

Use itertools.combinations:

from itertools import combinations

for combo in combinations(lst, 2): # 2 for pairs, 3 for triplets, etc
print(combo)

Python: Iterate over unique combinations in a list

I think you want itertools

import itertools
list(itertools.permutations([1,2,3...16],4)

EDIT

Or if you actually need the combination function, just use that.

import itertools
list(itertools.combinations([1,2,3...16],4)


Related Topics



Leave a reply



Submit