Home > Mobile >  Iteratively multiply elements of two lists in python
Iteratively multiply elements of two lists in python

Time:05-13

I have two lists (X and Y). I want to first scale the first element of X with all the elements of Y before moving to the second element of X which is then again scaled by all the elements of Y. How can I do this? Ideally, I would also like to append it to different lists (L) when a new element of X is started, but I am not sure if that is possible.

Y = [2, 3, 4, 5]
X = [1, 2, 3, 4]
L = []
for i in range(len(X)):
    for j in range(len(Y)):
        X_scale = X[i] * Y[j]
        L.append(X_scale)

Preferred outcome:

# First element in X
X_scale = [2, 2, 3, 4]
X_scale = [3, 2, 3, 4]
X_scale = [4, 2, 3, 4]
X_scale = [5, 2, 3, 4]

# Second element in X
X_scale = [1, 4, 3, 4]
X_scale = [1, 6, 3, 4]
#etc

CodePudding user response:

This seems to follow your pattern:

Y = [2, 3, 4, 5]
X = [1, 2, 3, 4]
L = []
for i,x in enumerate(X):
    for y in Y:
        X_scale = X.copy()
        X_scale[i] = x * y
        L.append(X_scale)

for row in L:
    print(row)

Output:

[2, 2, 3, 4]
[3, 2, 3, 4]
[4, 2, 3, 4]
[5, 2, 3, 4]
[1, 4, 3, 4]
[1, 6, 3, 4]
[1, 8, 3, 4]
[1, 10, 3, 4]
[1, 2, 6, 4]
[1, 2, 9, 4]
[1, 2, 12, 4]
[1, 2, 15, 4]
[1, 2, 3, 8]
[1, 2, 3, 12]
[1, 2, 3, 16]
[1, 2, 3, 20]

Per OP's comment to group the indices:

Y = [2, 3, 4, 5]
X = [1, 2, 3, 4]
L = []
for i,x in enumerate(X):
    L2 = []
    for y in Y:
        X_scale = X.copy()
        X_scale[i] = x * y
        L2.append(X_scale)
    L.append(L2)

for row in L:
    print(row)

Output:

[[2, 2, 3, 4], [3, 2, 3, 4], [4, 2, 3, 4], [5, 2, 3, 4]]
[[1, 4, 3, 4], [1, 6, 3, 4], [1, 8, 3, 4], [1, 10, 3, 4]]
[[1, 2, 6, 4], [1, 2, 9, 4], [1, 2, 12, 4], [1, 2, 15, 4]]
[[1, 2, 3, 8], [1, 2, 3, 12], [1, 2, 3, 16], [1, 2, 3, 20]]

CodePudding user response:

First you can simply you loops by accessing the items directly, without an index. Then you can transform the inner loop into a comprehension list to make it more compact:

Y = [2, 3, 4, 5]
X = [1, 2, 3, 4]
L = []
for x_item in X:
    L  = [x_item * y_item for y_item in Y]
  • Related