Python Initialize multidimensional numpy array of random value

Viewed 433

If I want to bulid a 3-dimensional array And I can write something like this (x is the 3-dimensional array)

for i in range(pN): 
    for j in range(C): 
        for k in range(K+1):
            X[i][j][k] = random.uniform(0,1) #random initialize

But how can I make this code to be more readable? (For example, don't use 3 for loop)

Thanks!

4 Answers

you can use numpy

import numpy as np
np.random.random((pN,C,K))

Use numpy instead.

First install it with

pip install -U numpy

In terminal or windows command prompt.

Then in python program import it with:

import numpy as np

And then use random.rand:

np.random.rand((pN,C,K))
import numpy as np

X = np.random.uniform(0, 1, (x, y, z))
# x, y, z would represent the size of each dimension

From the numpy documentation

Related