本文介绍了对numpy数组进行的操作包含大小不同的行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有两个列表,看起来像这样:
I have two lists, looking like this:
a= [[1,2,3,4], [2,3,4,5],[3,4,5,6,7]], b= [[5,6,7,8], [9,1,2,3], [4,5,6,7,8]]
我想逐个元素地相互减去以得到这样的输出:
which I want to subtract from each other element by element for an Output like this:
a-b= [[-4,-4,-4,-4],[7,2,2,2],[-1,-1,-1,-1,-1]]
为此,我将每个 a
和 b
都转换为数组,并减去它们,我使用:
In order to do so I convert each of a
and b
to arrays and subtract them I use:
np.array(a)-np.array(b)
输出只会给我错误:
我做错了什么? np.array
命令是否应确保转换为数组?
What am I doing wrong? Shouldn't the np.array
command ensure the conversion to the array?
推荐答案
您可以尝试:
>>> a= [[1,2,3,4], [2,3,4,5],[3,4,5,6,7]]
>>> b= [[5,6,7,8], [9,1,2,3], [4,5,6,7,8]]
>>>
>>> c =[]
>>> for i in range(len(a)):
c.append([A - B for A, B in zip(a[i], b[i])])
>>> print c
[[-4, -4, -4, -4], [-7, 2, 2, 2], [-1, -1, -1, -1, -1]]
或者第二种方法是使用地图:
Or 2nd method is using map:
from operator import sub
a= [[1,2,3,4], [2,3,4,5],[3,4,5,6,7]]
b= [[5,6,7,8], [9,1,2,3], [4,5,6,7,8]]
c =[]
for i in range(len(a)):
c.append(map(sub, a[i], b[i]))
print c
[[-4, -4, -4, -4], [-7, 2, 2, 2], [-1, -1, -1, -1, -1]]
这篇关于对numpy数组进行的操作包含大小不同的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!