Math with multiple lists in python

I am trying to get all possible combinations of three different lists in python

Say I have three lists

A = [2,3,4,7,9]
B = [2,3,5]
C = [1,2]

I want to return all combinations for which A [i] + B [j] -C [k] == 3 is true

D = [[i,j,k] for i in A for j in B for k in C]

which gives me all the combinations in list format, but how to proceed here?

+4
source share
3 answers

You can use list comprehension with itertools.productto check each combination to see if it matches your criteria.

>>> from itertools import product
>>> [(a,b,c) for a,b,c in product(A,B,C) if a + b - c == 3]
[(2, 2, 1), (2, 3, 2), (3, 2, 2)]
+2
source

Just add if i+j-k == 3. You do not want A[i], etc., since it indexes each list, whereas i, jand kare already the elements themselves.

D = [[i,j,k] for i in A for j in B for k in C if i+j-k == 3]

itertools.product, :

import itertools
D = [[i,j,k] for i,j,k in itertools.product(A, B, C) if i+j-k == 3]
+2

:

>>> D = [[i,j,k] for i in A for j in B for k in C if i + j - k == 3]
>>> D
[[2, 2, 1], [2, 3, 2], [3, 2, 2]]
0

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


All Articles