对numpy数组进行的操作包含大小不同的行 [英] Operation on numpy arrays contain rows with different size

查看:54
本文介绍了对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)

输出只会给我错误:

以下类型不受支持的操作数类型:列表"和列表"

Unsupported Operand type for-: 'list' and 'list'

我做错了什么? 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数组进行的操作包含大小不同的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆