initialize a numpy array

前端 未结 12 1683
情歌与酒
情歌与酒 2020-11-28 02:55

Is there way to initialize a numpy array of a shape and add to it? I will explain what I need with a list example. If I want to create a list of objects generated in a loop,

12条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-28 03:25

    Maybe something like this will fit your needs..

    import numpy as np
    
    N = 5
    res = []
    
    for i in range(N):
        res.append(np.cumsum(np.ones(shape=(2,4))))
    
    res = np.array(res).reshape((10, 4))
    print(res)
    

    Which produces the following output

    [[ 1.  2.  3.  4.]
     [ 5.  6.  7.  8.]
     [ 1.  2.  3.  4.]
     [ 5.  6.  7.  8.]
     [ 1.  2.  3.  4.]
     [ 5.  6.  7.  8.]
     [ 1.  2.  3.  4.]
     [ 5.  6.  7.  8.]
     [ 1.  2.  3.  4.]
     [ 5.  6.  7.  8.]]
    

提交回复
热议问题