迭代乘以 python 中的两个列表的元素
Iteratively multiply elements of two lists in python
我有两个列表(X
和 Y
)。我想先用 Y
的所有元素缩放 X
的第一个元素,然后再移动到 X
的第二个元素,然后再次按 [=14= 的所有元素缩放].我怎样才能做到这一点?理想情况下,我还想在启动 X 的新元素时将其附加到不同的列表 (L
),但我不确定这是否可能。
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)
首选结果:
# 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
首先,您可以通过直接访问项目来简单地循环,而无需索引。然后你可以将内层循环转化为一个理解列表,使其更紧凑:
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]
这似乎符合您的模式:
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)
输出:
[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]
根据 OP 对索引进行分组的评论:
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)
输出:
[[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]]
我有两个列表(X
和 Y
)。我想先用 Y
的所有元素缩放 X
的第一个元素,然后再移动到 X
的第二个元素,然后再次按 [=14= 的所有元素缩放].我怎样才能做到这一点?理想情况下,我还想在启动 X 的新元素时将其附加到不同的列表 (L
),但我不确定这是否可能。
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)
首选结果:
# 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
首先,您可以通过直接访问项目来简单地循环,而无需索引。然后你可以将内层循环转化为一个理解列表,使其更紧凑:
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]
这似乎符合您的模式:
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)
输出:
[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]
根据 OP 对索引进行分组的评论:
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)
输出:
[[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]]