Home > Mobile >  Combine into a flat list in python
Combine into a flat list in python

Time:09-17


I want to :

  1. Iterate through the elements of the first list, a
  2. Multiply them by the elements in the second list b
  3. Then subtract the elements in a third list c

e.g:

a = [1,2]
b = [0,1]
c = [1,2]
output = [-1, -2, 0, -1, -1, -2, 1, 0]

CodePudding user response:

import numpy as np

a = [1,2]
b = [0,1]
c = [1,2]
o = [-1, -2, 0, -1, -1, -2, 1, 0]

A = np.array(a)[:, None, None]
B = np.array(b)[None, :, None]
C = np.array(c)[None, None, :]
O = (A * B - C).ravel()
print(O)
# [-1 -2  0 -1 -1 -2  1  0]

np.allclose(o, O)
# True

CodePudding user response:

a = [1,2]
b = [0,1]
c = [1,2]

result = [((x*y)-z) for x in a for y in b for z in c]
print(result)

Here is one possible answer

CodePudding user response:

Try that

a = [1,2]
b = [0,1]
c = [1,2]
result= []

for i in a:
    for j in b:
        aux = i*j
        for z in c:
            res = aux - z
            result.append(res)

print(result)
  • Related