Python乘以2个数组

时间:2011-04-28 22:14:10

标签: python arrays

这是从线程继续: Python array multiply

我需要将数组与数组相乘。我不想使用“numpy”。从前一个帖子开始,我学会了如何乘法

号*数组:

hh=[[82.5], [168.5]]
N=1./5
ll = [[x*N for x in y] for y in hh]

但是如何将数组*数组相乘: - > 矩阵乘法。

hh=[[82.5], [168.5]]
N=zip(*hh)                                        -> N must be transpose of hh!!!!!
ll = [[[x*z for x in y] for y in hh] for z in N]

?感谢


编辑:

输入:

hh=[[82.5], [168.5]]
N=zip(*hh)                            #N=[(82.5, 168.5)]

输出 想:hh * N

[[  6806.25  13901.25]
 [ 13901.25  28392.25]]

4 个答案:

答案 0 :(得分:3)

你的想法是对的,但你可以把它写得更简单:

list_a = [1,2,3,4,5] # or hh[0]
list_b = [6,7,8,9,0] # or hh[1]
multiplied = [a * b for a, b in zip(list_a, list_b)]

此外,如果您希望/运算符返回浮点数,请在源代码顶部添加from __future__ import division

答案 1 :(得分:3)

您可以使用列表理解,就像之前的数字*数组问题一样。

假设您有两个阵列:

a = [1,2,3]
b = [4,5,6]

首先你zip获得你想要成倍增加的对:

pairs = zip(a,b)

这导致[(1, 4), (2, 5), (3, 6)]。 你可以像这样“解包”一个元组:

val1, val2 = (1,4) # val1=1 and val2=4

将所有内容组合在一起,这将是多个数组ab

c = [val1*val2 for val1,val2 in zip(a,b)]

在上面的示例中,hh是一个包含两个数组的数组,答案变为:

hh=[[82.5], [168.5]]
N=zip(*hh)
ll = [x*y for x,y in N]

答案 2 :(得分:2)

使用operator.mul和map。

from operator import mul
map(mul, list1, list2)

矩阵N * hh,其中N = zip(** hh)

>>> hh = [[82.5], [168.5]]
>>> [ [i*j for i in x for j in y] for x in hh for y in zip(*hh) ]
[[6806.25, 13901.25], [13901.25, 28392.25]]

>>> hh = [[2], [4]]
>>> [ [i*j for i in x for j in y] for x in hh for y in zip(*hh) ]
[[4, 8], [8, 16]]

>>> hh = [[2], [4], [6]]
>>> [ [i*j for i in x for j in y] for x in hh for y in zip(*hh) ]
[[4, 8, 12], [8, 16, 24], [12, 24, 36]]

>>> hh = [[1, 2, 4]]
>>> [ [i*j for i in x for j in y] for x in hh for y in zip(*hh) ]
[[1, 2, 4], [2, 4, 8], [4, 8, 16]]

>>> hh = [[1, 2], [3, 4]]
>>> [ [i*j for i in x for j in y] for x in hh for y in zip(*hh) ]
[[1, 3, 2, 6], [2, 4, 4, 8], [3, 9, 4, 12], [6, 12, 8, 16]]

如果您正在寻找其他内容,这里有另外两个例子可以帮助您入门:

>>> a = [1, 2, 3]
>>> b = [0, 1, 2]
>>> [ x*y for x in a for y in b]
[0, 1, 2, 0, 2, 4, 0, 3, 6]
>>> [[x*y for x in a] for y in b]
[[0, 0, 0], [1, 2, 3], [2, 4, 6]]

答案 3 :(得分:1)

基于上一个问题,我假设你想要矩阵乘法,而不是逐元素乘法......

m = range(len(hh))
n = range(len(N[0]))
p = range(len(N))
ll = [[sum(hh[i][k]*N[k][j] for k in p) for j in n] for i in m]