python创建随机数组_如何在一定范围内创建随机数组

我建议手工生成并在稍后创建列表:import numpy as np

i = np.random.uniform(1.5, 12.4)

j = np.random.randint(0, 5) # 5 not included use (0, 6) if 5 should be possible

k = np.random.randint(4, 16) # dito

l = np.random.randint(3, 5) # dito

m = np.random.uniform(2.4, 8.9.)

array = np.array([i, j, k, l, m]) # as numpy array

# array([ 3.33114735, 3. , 14. , 4. , 4.80649945])

array = [i, j, k, l, m] # or as list

# [3.33114735, 3, 14, 4, 4.80649945]

如果要一次性创建它们,可以使用np.random.random使用范围和下限来修改它们,并将它们转换为不需要浮动的整数:# Generate 5 random numbers between 0 and 1

rand_numbers = np.random.random(5)

# Lower limit and the range of the values:

lowerlimit = np.array([1.5, 0, 4, 3, 2.4])

dynamicrange = np.array([12.4-1.5, 5-0, 16-4, 5-3, 8.9-2.4]) # upper limit - lower limit

# Apply the range

result = rand_numbers * dynamicrange + lowerlimit

# convert second, third and forth element to integer

result[1:4] = np.floor(result[1:4])

print(result)

# array([ 12.32799347, 1. , 13. , 4. , 7.19487119])

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
创建一个包含随机元素的数组(集合)在Python中,您可以使用`random.sample()`方法来选取特定数量的独特元素。此方法适用于从一个已存在的序列中提取元素而不重复。 假设我们有一个序列 `seq` 包含一系列数值: ```python seq = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] ``` 要从中生成一个由4个独特随机元素组成的数组,可以执行以下操作: ```python import random # 定义序列并设置所需随机元素的数量 seq = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] n = 4 # 使用random.sample生成包含n个不同元素的随机子集 sampled_elements = random.sample(seq, n) print(sampled_elements) ``` 这将会输出类似于 `[3, 1, 7, 9]` 的结果,但每次运行可能会不同,因为它是随机选择的。 关于您提到的其他生成随机数字的方法,它们各自用于生成不同类型的随机值: 1. **`random.randint(a, b)`**:生成一个在闭区间 `[a, b]` 内的随机整数。 ```python result = random.randint(1, 10) ``` 2. **`random.random()`**:生成一个在区间 `(0.0, 1.0)` 内的随机浮点数。 ```python result = random.random() ``` 3. **`random.uniform(a, b)`**:生成一个在闭区间 `[a, b]` 内的随机浮点数。 ```python result = random.uniform(1.0, 10.0) ``` 4. **`random.randrange(start, stop[, step])`**:生成一个指定步长范围内的随机整数。 ```python result = random.randrange(1, 10, 2) # 生成奇数范围内的随机数 ``` 请注意,为了确保上述代码片段能够正常工作,记得导入相应的 `random` 模块: ```python from random import * ``` --- ## 相关问题: 1. 如何利用`random.shuffle()`对一个列表进行随机排列? 2. `random.choice()`与`random.sample()`有何区别? 3. 怎样生成一个指定长度的全随机字符数组
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值