Python 生成随机数组
时间: 2024-04-10 09:25:32 浏览: 12
以下是使用Python生成随机数组的两种方法[^1][^2]:
1. 使用random模块的sample函数生成随机数组:
```python
import random
seq = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
random_array = random.sample(seq, 4)
print(random_array) # 输出:[7, 3, 1, 9]
```
2. 使用numpy库生成随机数组:
```python
import numpy as np
random_array = np.random.randint(1, 10, size=4)
print(random_array) # 输出:[7, 3, 1, 9]
```
相关问题
python生成随机数组
可以使用Python中的random模块来生成随机数组,具体实现可以参考以下代码:
import random
# 生成长度为10的随机数组
arr = [random.randint(1,100) for i in range(10)]
print(arr)
输出结果:
[14, 54, 80, 70, 94, 51, 6, 67, 55, 19]
python 随机生成数组
要在Python中随机生成数组,可以使用random模块或numpy.random模块中的函数。在random模块中,可以使用random_int_list函数来生成一个指定范围内的随机整数数组。该函数接受三个参数,分别是起始值、结束值和数组长度。例如,random_int_list(1, 100, 10)将生成一个长度为10的整数数组,其中的元素在1到100之间。\[1\]
另外,在numpy库中,可以使用np.random.rand函数来生成一个指定长度的随机浮点数数组。当没有参数时,该函数返回一个随机浮点数;当有一个参数时,返回该参数长度大小的一维随机浮点数数组。例如,np.random.rand(10)将生成一个长度为10的随机浮点数数组,其中的元素在0.0到1.0之间。\[3\]
所以,根据你的需求,你可以选择使用random模块的random_int_list函数或numpy.random模块的np.random.rand函数来生成随机数组。
#### 引用[.reference_title]
- *1* *3* [python生成随机数组](https://blog.csdn.net/healthy_coder/article/details/50502643)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item]
- *2* [python如何随机生成数组](https://blog.csdn.net/weixin_39819671/article/details/111074705)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item]
[ .reference_list ]