不使用for添加两个数组. Python [英] Add two arrays without using for. Python

查看:94
本文介绍了不使用for添加两个数组. Python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下两个数组:

import numpy as np
a = np.array([0, 10, 20])
b = np.array([20, 30, 40, 50])  

我想通过以下两种方式添加两者,同时避免缓慢的Python for循环:

I´d like to add both in the following way while avoiding slow Python for loops:

c = array([20, 30, 40, 50, 30, 40, 50, 60, 40, 50, 60, 70])

这意味着,对于"a"的第一个元素,添加b的所有元素,然后为第二个元素添加,依此类推.

It means, for the first element of "a" add all the elements of b,then for the second element and so on.

我知道这似乎很容易,但是对于庞大的数组,Python循环太慢了.

I know it seems quite easy, but for huge arrays Python loops are too slow.

谢谢.

推荐答案

在这里:

In [17]: a = np.array([0, 10, 20])

In [18]: b = np.array([20, 30, 40, 50])  

In [19]: (a.reshape(-1, 1) + b).ravel()
Out[19]: array([20, 30, 40, 50, 30, 40, 50, 60, 40, 50, 60, 70])

这是详细信息.

a.reshape(-1, 1)a转换为形状为(3,1)的数组:

a.reshape(-1, 1) converts a to an array with shape (3, 1):

In [20]: a.reshape(-1, 1)
Out[20]: 
array([[ 0],
       [10],
       [20]])

在其中添加b时,广播适用,实际上是做一个外部总和"(即将所有成对组合相加),从而形成形状为(3,4)的数组:

When b is added to that, broadcasting applies, which in effect does an "outer sum" (i.e. adds all the pairwise combinations), forming an array with shape (3, 4):

In [21]: a.reshape(-1, 1) + b
Out[21]: 
array([[20, 30, 40, 50],
       [30, 40, 50, 60],
       [40, 50, 60, 70]])

ravel()方法展平结果变成一维数组:

The ravel() method flattens the result into a one-dimensional array:

In [22]: (a.reshape(-1, 1) + b).ravel()
Out[22]: array([20, 30, 40, 50, 30, 40, 50, 60, 40, 50, 60, 70])

有关更简洁的版本,请参见@HYRY的答案.

See @HYRY's answer for an even more concise version.

这篇关于不使用for添加两个数组. Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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