如何将一个数组乘以随机数 [英] How to multiply array of ones by random numbers

查看:54
本文介绍了如何将一个数组乘以随机数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将数组中的每个值乘以一个随机数.每次我尝试使用迭代方法时,都会收到一条错误消息:IndexError: index out of bounds".这是我的代码:

来自物理导入 *N = 3.0x = 个(N)对于 x 中的 i:x[i] = i * 统一(10)

Numpy 存储在物理导入中.

我已经这样做了,这样当我回来时,我可以通过更改 N 的值轻松更改数组中的数字.

解决方案

除非您必须使用 physics 库,否则请使用以下代码:

<预><代码>>>>随机导入>>>数组 = [1]*random.randint(1, 10)>>>大批[1, 1, 1, 1, 1]>>>对于 enumerate(array) 中的 i, j:... array[i] = j*random.randint(1, 10)...>>>大批[3, 7, 5, 1, 2]>>>

您的代码无法正常工作,因为您正在执行 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆