Python:从数组维度获取随机值

时间:2012-10-21 11:17:09

标签: python arrays random numpy

我试图从Python中的数组单维获取随机元素。所以在下面的例子中,我想检索5个花车中的任何一个。

ar = rand(1, 5)

ar = array([[ 0.29889882,  0.84955019,  0.52989055,  0.57220576,  0.16841406]])

如果有5个元素且只有一个维度,我已经能够检索浮点数 (ar = rand(5, 1)),

使用:

ar[randrange(0, p.size)]

但如何从单个维度获取数组中的值?

2 个答案:

答案 0 :(得分:0)

假设您指的是numpy.array,您可以使用以下内容:

>>> import numpy as np
>>> np.array([[ 0.29889882, 0.84955019, 0.52989055, 0.57220576, 0.16841406]])
array([[ 0.29889882,  0.84955019,  0.52989055,  0.57220576,  0.16841406]])
>>> 
>>> 
>>> ar = np.array([[ 0.29889882, 0.84955019, 0.52989055, 0.57220576, 0.16841406]])
>>> ar[:, random.randint(0,4)]
array([ 0.29889882])
>>> ar[:, random.randint(0,4)]
array([ 0.52989055])

答案 1 :(得分:0)

让我们这样说:

ar = rand(1, 5)

ar = array([[ 0.29889882, 0.84955019, 0.52989055, 0.57220576, 0.16841406]])

#create a generator object that returns random values from your array

def getGen(array):
    def gen(arr):
        yield arr[:,ramdom.randint(0,(array.size - 1))] #yielding random values
    return gen(array) # returning generator object

genFromArray = getGen(ar) #getting generator
genFromArray() #would return a random value from your array