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!

4

3 に答える 3

2

これは 3 つの次元配列です。次の方法で作成できます。

np.random.randint(0, 100, (100, 100, 2))
于 2013-03-28T12:02:23.033 に答える
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]
于 2013-03-28T12:22:41.863 に答える
0

あなたが何をしようとしているのか理解できれば、@HYRYは正しい答えを出します.Valueエラーが発生する理由は、シーケンスまたはpythonリスト(tmp)を単一のfloat( a[i][j] )。@HalCana​​ry は、コードを修正してこのエラーを回避する方法を示していますが、HYRY のコードは Python コンピューティングに最適なはずです。

于 2013-03-30T00:27:18.587 に答える