python中np.random.permutation
时间: 2025-01-31 07:33:17 浏览: 49
### Python中NumPy库`random.permutation`函数的使用
#### 函数概述
`np.random.permutation(x)`用于随机排列序列。如果传入的是整数,则会先构建一个从 `0` 到该整数值减一的数组再进行随机排列;如果是多维数组则只沿第一个轴打乱元素位置[^1]。
#### 使用示例
##### 示例 1:对列表或一维数组执行随机排列
当输入为一维数组时,将会返回一个新的含有相同元素但是顺序被打乱的一维数组:
```python
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
permuted_arr = np.random.permutation(arr)
print("原始数组:", arr)
print("随机排列后的数组:", permuted_arr)
```
上述代码可能会输出如下结果:
```
原始数组: [1 2 3 4 5]
随机排列后的数组: [3 1 4 5 2]
```
##### 示例 2:对指定范围内整数执行随机排列
对于给定的一个正整数n作为参数传递给此函数,它将创建并返回长度为n且由 `[0,..., n-1]` 组成的新数组,并对其进行随机重排:
```python
permuted_range = np.random.permutation(10)
print("随机排列后的范围:", permuted_range)
```
这可能得到像这样的输出:
```
随机排列后的范围: [4 2 8 1 9 0 7 3 5 6]
```
##### 示例 3:处理二维或多维数组的情况
当应用于更高维度的数据结构时,仅会对最外层(即第一轴)上的子数组做重新排序操作而不影响内部数据布局:
```python
matrix = np.arange(12).reshape((4, 3))
shuffled_matrix = np.random.permutation(matrix)
print("原矩阵:\n", matrix)
print("\n经过permutation之后的结果:\n", shuffled_matrix)
```
这段程序可以产生类似以下形式的结果:
```
原矩阵:
[[ 0 1 2]
[ 3 4 5]
[ 6 7 8]
[ 9 10 11]]
经过permutation之后的结果:
[[ 6 7 8]
[ 0 1 2]
[ 9 10 11]
[ 3 4 5]]
```
阅读全文
相关推荐
















