如何使用numpy在数组中添加任何两个元素并生成矩阵? [英] How to use numpy to add any two elements in an array and produce a matrix?

查看:188
本文介绍了如何使用numpy在数组中添加任何两个元素并生成矩阵?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

原生python代码如下:

The native python codes are like this:

>>> a=[1,2,3,4,5,6]
>>> [[i+j for i in a] for j in a]
[[2, 3, 4, 5, 6, 7], 
 [3, 4, 5, 6, 7, 8], 
 [4, 5, 6, 7, 8, 9], 
 [5, 6, 7, 8, 9, 10], 
 [6, 7, 8, 9, 10, 11], 
 [7, 8, 9, 10, 11, 12]]

但是,由于数组很大,我必须使用numpy来完成这项工作. 有人在 numpy 中有关于如何执行相同工作的想法吗?

However, I have to use numpy to do this job as the array is very large. Does anyone have ideas about how to do the same work in numpy?

推荐答案

许多NumPy二进制运算符都有一个outer方法,该方法可用于形成一个乘法(或在这种情况下为加法)表的等效项:

Many NumPy binary operators have an outer method which can be used to form the equivalent of a multiplication (or in this case, addition) table:

In [260]: import numpy as np
In [255]: a = np.arange(1,7)

In [256]: a
Out[256]: array([1, 2, 3, 4, 5, 6])

In [259]: np.add.outer(a,a)
Out[259]: 
array([[ 2,  3,  4,  5,  6,  7],
       [ 3,  4,  5,  6,  7,  8],
       [ 4,  5,  6,  7,  8,  9],
       [ 5,  6,  7,  8,  9, 10],
       [ 6,  7,  8,  9, 10, 11],
       [ 7,  8,  9, 10, 11, 12]])

这篇关于如何使用numpy在数组中添加任何两个元素并生成矩阵?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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