2

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 4

2

Just use numpy random function:

https://docs.scipy.org/doc/numpy-1.15.1/reference/generated/numpy.random.rand.html

It will generate random array of a shape you want (like 3x2x3)

 np.random.rand(3,2,3)
Sign up to request clarification or add additional context in comments.

Comments

1

you can use numpy

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

Comments

1

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))

Comments

1
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.