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]]
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?
解决方案
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]])