以下是一个来自Python 2.7.3解释器会话的文字记录,展示了使用内置函数
map
对2D矩阵元素进行逐元素操作的过程。 (注意:
operator.add
等同于问题中指定的
elementwise_function
,也等同于第二次使用
applier
的lambda表达式。)
>>> import operator
>>> def applier(a, b, op):
... return map(lambda ro: map(op, ro[0], ro[1]), zip(a,b))
...
>>> applier(x, y, operator.add)
[[5, 5, 2], [5, 4, 5], [6, 5, 5]]
>>> x; y
[[2, 2, 1], [2, 2, 2], [3, 2, 2]]
[[3, 3, 1], [3, 2, 3], [3, 3, 3]]
>>> applier(x, y, lambda p,q: p+q)
[[5, 5, 2], [5, 4, 5], [6, 5, 5]]
>>> applier(x, y, lambda p,q: p-q)
[[-1, -1, 0], [-1, 0, -1], [0, -1, -1]]
>>> applier(x, y, lambda p,q: p*q)
[[6, 6, 1], [6, 4, 6], [9, 6, 6]]
请注意,上述内容的x和y如下:
x=[[2, 2, 1], [2, 2, 2], [3, 2, 2]]
y=[[3, 3, 1], [3, 2, 3], [3, 3, 3]]
如前所述,上面的转录是从Python 2.7.3解释器会话中得出的。如果在Python 3中运行此代码,则会返回map对象。可以使用以下函数查看数字:
def itemize(m):
return [itemize(e) for e in m] if hasattr(m, '__iter__') else m
有了这个函数,语句变成:
itemize(applier(x, y, operator.add))
返回值
[[5, 5, 2], [5, 4, 5], [6, 5, 5]]
z = x + y
在你上面的例子中可以工作。也许你可以展示一下你的函数,我们可以帮助你在矩阵上使其正常工作? - mathematical.coffee