Python NumPy中 -1 的作用 及 NumPy.random.randint()的简单说明

Python代码中经常会遇到 -1 这个数字,它主要有两个作用:

  1. 倒数第一
  2. 自动推断

倒数第一

在list, tuple, array中表示倒数第一个

简单举例

a01 = [3, 2]                                        
print("a01[:-1]:", a01[:-1])        # output: 3     
print("a01[0:-1]:", a01[0:-1])      # output: 3     

复杂举例

大原则:左闭(inclusive)右开(exclusive)原则

【重要】这个原则在整个Python代码中都适用。
以NumPy.random.randint这个函数举例说明。

np.random.randint

randint(low, high=None, size=None, dtype=‘l’)
Return random integers from low (inclusive) to high (exclusive).
返回值:随机整数矩阵,范围:[low, high) 。
Return random integers from the “discrete uniform” distribution of
the specified dtype in the “half-open” interval [low, high).
返回指定数据类型的随机整数矩阵,其满足 “离散均匀”分布,其所在区间为半开区间[low, high)
If high is None (the default), then results are from [0, low).
如果high没有指定,则返回值范围是[0,low).
Parameters
----------
size : int or tuple of ints, optional
整数或者整数元组,这个参数是可选的,不是必须提供的。
Output shape. 返回值的形状。
If the given shape is, e.g., (m, n, k), then m * n * k samples are drawn.
如果 size 被指定为(m, n, k),则返回值是这种形状m * n * k的矩阵。
Default is None, in which case a single value is returned.
默认值为None,此时返回一个整数。

Returns
-------
out : int or ndarray of ints

### np.random.randint 的用法示例 `np.random.randint` 是 NumPy 库中用于生成随机整数的函数,支持生成单个整数或指定形状的整数数组。该函数的基本语法为: ```python np.random.randint(low, high=None, size=None, dtype='l') ``` 其中: - `low`:最小的整数值(包含)。 - `high`:最大的整数值(不包含),若未提供,则取值范围为 `[0, low)`。 - `size`:输出数组的形状,可以是整数或元组。 - `dtype`:返回数据的类型,默认为 `np.int`。 #### 生成单个随机整数 以下代码生成一个介于 `0` 和 `9` 之间的随机整数(包含 `0`,不包含 `10`): ```python import numpy as np single_random_int = np.random.randint(10) print(single_random_int) ``` 此代码可能输出如 `7` 的结果[^2]。 #### 生成一维随机整数数组 生成一个长度为 5 的一维数组,数组元素在 `0` 到 `9` 之间: ```python random_array = np.random.randint(10, size=5) print(random_array) ``` 此代码可能输出如 `[2 5 1 8 3]` 的结果。 #### 生成二维随机整数矩阵 生成一个 `3x3` 的矩阵,元素值在 `5` 到 `15` 之间: ```python random_matrix = np.random.randint(5, 16, size=(3, 3)) print(random_matrix) ``` 此代码可能输出如: ``` [[ 7 10 14] [12 6 9] [15 8 11]] ``` 的结果[^2]。 #### 生成负数范围内的随机整数数组 生成一个 `2x3` 的数组,元素值在 `-5` 到 `10` 之间: ```python random_array = np.random.randint(-5, 10, size=(2, 3)) print(random_array) ``` 此代码可能输出如: ``` [[-2 3 0] [ 7 -4 9]] ``` 的结果[^3]。 #### 指定数据类型 生成一个 `1x5` 的数组,并指定数据类型为 `int64`: ```python random_array = np.random.randint(1, 10, size=(1, 5), dtype='int64') print(random_array) ``` 此代码可能输出如 `[[3 7 2 5 9]]` 的结果[^4]。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值