我有兩個列表,我想將第一個列表中的每個數字乘以第二個列表中的所有數字
[1,2]x[1,2,3]
我希望我的結果是這樣的 [(1x1)+(1x2)+(1x3),(2x1)+(2x2)+(2x3)]
a = np.array([1,2])
b = np.array([1,2,3])
c = (a[:,None]*b).sum(1)
輸出: array([ 6, 12])
a = [1,2]
b = [1,2,3]
c = [sum(x*y for y in b) for x in a]
輸出: [6, 12]
a = np.array([1,2])
b = np.array([1,2,3])
c = (a[:,None]*b).ravel()
輸出: array([1, 2, 3, 2, 4, 6])
a = [1,2]
b = [1,2,3]
c = [x*y for x in a for y in b]
## OR
from itertools import product
c = [x*y for x,y in product(a,b)]
輸出: [1, 2, 3, 2, 4, 6]
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句