如何将一个数组乘以随机数 [英] How to multiply array of ones by random numbers
问题描述
我正在尝试将数组中的每个值乘以一个随机数.每次我尝试使用迭代方法时,都会收到一条错误消息:IndexError: index out of bounds".这是我的代码:
来自物理导入 *N = 3.0x = 个(N)对于 x 中的 i:x[i] = i * 统一(10)
Numpy 存储在物理导入中.
我已经这样做了,这样当我回来时,我可以通过更改 N
的值轻松更改数组中的数字.
除非您必须使用 physics
库,否则请使用以下代码:
您的代码无法正常工作,因为您正在执行 for i in x
,即将 i
分配给 x
的每个值.相反,将 for i in x
更改为 for i in range(0, len(x))
或 for i in range(len(x))代码>.
I am trying to multiply each value in my array of ones by a random number. Each time I try by a method of iteration, I get an error saying: 'IndexError: index out of bounds.' Here is my code:
from physics import *
N = 3.0
x = ones(N)
for i in x:
x[i] = i * uniform(10)
Numpy is stored in the physics import.
I've done it this way so that when I come back I can easily change the number of ones in my array by changing my value of N
.
Unless you have to use the physics
library, use this code:
>>> import random
>>> array = [1]*random.randint(1, 10)
>>> array
[1, 1, 1, 1, 1]
>>> for i, j in enumerate(array):
... array[i] = j*random.randint(1, 10)
...
>>> array
[3, 7, 5, 1, 2]
>>>
Your code isn't working because you are doing for i in x
, which is assigning i
to every value of x
. Instead, change the for i in x
to for i in range(0, len(x))
or for i in range(len(x))
.
这篇关于如何将一个数组乘以随机数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!