Skip to main content
 首页 » 编程设计

python之根据结构化数组python中的条件生成随机值

2025年05月04日14lovecherry

我有一个表示位置 (x,y) 和颜色 (r,g,b) 的数组。现在数组变成全零(因为它应该)。我需要使 x 和 y 的值是随机的并且 <=10。我需要使 r、g 和 b 的值也是随机的,但 <=255。您如何指定只为“位置”生成 10,同样为“颜色”生成 255。

array = np.zeros(10, [ ('position', [ ('x', float, 1), 
                                   ('y', float, 1)]), 
                    ('color',    [ ('r', float, 1), 
                                   ('g', float, 1), 
                                   ('b', float, 1)])]) 

请您参考如下方法:

试试这个:

import random  
import numpy 
 
array = numpy.zeros(10, [ ('position', [ ('x', float, 1), 
                                   ('y', float, 1)]), 
                    ('color',    [ ('r', float, 1), 
                                   ('g', float, 1), 
                                   ('b', float, 1)])]) 
 
 
ranPos = lambda: random.random() * 10 
ranColor = lambda: random.random() * 255 
 
for i in range(10): 
    array[i] = ((ranPos(), ranPos()), 
                (ranColor(), ranColor(), ranColor())) 

如果你想生成整数,请改用它:

ranPos = lambda: random.randint(0,10) 
ranColor = lambda: random.randint(0,255)