0

Hi im sure there is a much more efficient way of coding this, im primarily a java programmer but trying to help some one out with some basic python.

I need to have a 2D array which contains a set of random co-ordinates eg (2, 10). My initial thought was to create the array then fill it will smaller arrays containing the two co-ordinates.

import numpy
import random

a = numpy.zeros(10000).reshape(100, 100)
temp = []
for i in range(0,100):
    for j in range(0,100):
        temp.append(random.randint(0,100))
        temp.append(random.randint(0,100))
        a[i][j]=temp

print a

This produces the error ValueError: setting an array element with a sequence.

So whats the best way to go about solving this problem? Sorry for this hacked together code i've never really had to use python before!

3 Answers 3

2

That is a three dim array, you can create it by:

np.random.randint(0, 100, (100, 100, 2))
Sign up to request clarification or add additional context in comments.

3 Comments

will that create a 100 * 100 array with the co ordinates ?
@user2219545 That's a 100 * 100 * 2 array, where the two coordinates use the last dimension.
@user2219545 Janne means to say Yes!.
0
import numpy
import random
a = numpy.zeros((100, 100, 2))
for i in range(0,100):
    for j in range(0,100):
        a[i,j,:] = (random.randint(0,100),
                    random.randint(0,100))
print 'x-coords:\n', a[:,:,0]
print 'y-coords:\n', a[:,:,1]

Comments

0

@HYRY gives the correct answer if I understand what you are trying to do.. The reason you get a Value error is because you are assigning a sequence, or python list (tmp) to a single float ( a[i][j] ). @HalCanary shows you how to do fix your code to get around this error, but HYRY's code should be optimal for python computing.

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.