簡體   English   中英

如何將 python 列表中的每個元素與另一個列表中的元素相乘?

[英]How can i multiply each element in a python list with element in another list?

x = [5,10,15,20,25,30] y = [60,90,120,150,190,200]

我想將 5x60、10x90、15x120、20x150、25x190、30x200 相乘並將它們存儲在 z=[] 中,我該怎么做? 謝謝,我已經嘗試過了,但是它將每個元素與 x 中的所有元素與 y 中的所有元素相乘

***x = [5,10,15,20,25,30]
y = [60,90,120,150,190,200]
sumx= sum(x)
sumy=sum(y)
for i in x:
    z=[i* j for j in y]
    print(z)***

結果

[300, 450, 600, 750, 950, 1000]
[600, 900, 1200, 1500, 1900, 2000]
[900, 1350, 1800, 2250, 2850, 3000]
[1200, 1800, 2400, 3000, 3800, 4000]
[1500, 2250, 3000, 3750, 4750, 5000]
[1800, 2700, 3600, 4500, 5700, 6000]

你可以這樣做:

ans = [i*j for i, j in zip(x, y)]

[300, 900, 1800, 3000, 4750, 6000]

如果您打算使用 arrays 進行大量算術運算,您可能需要考慮使用 numpy。

import numpy as np

x = np.array([5,10,15,20,25,30])
y = np.array([60,90,120,150,190,200])
result = x * y

如果這只是一次性的事情,那么@Jarvis 的解決方案絕對是正確的答案。

發現這個工作:

x = [5,10,15,20,25,30]
y = [60,90,120,150,190,200]
a = 0
z = []
for i in range(len(x)):
    z.append(x[a] * y[a])
    a += 1
print(z)

得到這個作為 output:

[300, 900, 1800, 3000, 4750, 6000]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM