Reputation: 1
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!
Upvotes: 0
Views: 1250
Reputation: 5362
@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.
Upvotes: 0
Reputation: 2240
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]
Upvotes: 0
Reputation: 97261
That is a three dim array, you can create it by:
np.random.randint(0, 100, (100, 100, 2))
Upvotes: 2