简体   繁体   中英

Are there alternative way to manage value assignment of n-dim array/matrix/list in Python?

In python we do some thing like this for example:

n = 30
A = numpy.zeros(shape=(n,n))

for i in range(0, n):
    for j in range(0, n):
        A[i, j] = i+j 
        #i+j just example of assignment

To manage a 2-dim array. It's so simple. just use nest loop to walk around rows and columns.

But my friend told me why it's so complicated. Could you give me the another way to manage it?

He told me in Mathematica have some way more easier to manage n-dim array (I'm not sure. I've never use Mathematica)

Can you give me the alternative way to manage value assignment on n-dim matrix/array(in Numpy) or list(ordinary one in Python)?

You are looking for numpy.fromfunction :

>>> numpy.fromfunction(lambda x, y: x + y, (5, 5))
array([[ 0.,  1.,  2.,  3.,  4.],
       [ 1.,  2.,  3.,  4.,  5.],
       [ 2.,  3.,  4.,  5.,  6.],
       [ 3.,  4.,  5.,  6.,  7.],
       [ 4.,  5.,  6.,  7.,  8.]])

You can simplify slightly using operator :

>>> from operator import add
>>> numpy.fromfunction(add, (5, 5))
array([[ 0.,  1.,  2.,  3.,  4.],
       [ 1.,  2.,  3.,  4.,  5.],
       [ 2.,  3.,  4.,  5.,  6.],
       [ 3.,  4.,  5.,  6.,  7.],
       [ 4.,  5.,  6.,  7.,  8.]])

You can use the mathematical rules for matrixes and vectors:

n = 30
w = numpy.arange(n).reshape(1,-1)
A = w+w.T

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM