Python代码中经常会遇到 -1 这个数字,它主要有两个作用:
- 倒数第一
- 自动推断
倒数第一
在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,此时返回一个整数。</