gpt4 book ai didi

python - numpy : indexes too big giving sometimes exceptions, 有时不是

转载 作者:行者123 更新时间:2023-12-01 03:21:32 24 4
gpt4 key购买 nike

这看起来真的很愚蠢,但我想知道为什么下面的代码(numpy 1.11.2)会引发异常:

import numpy as npy
a = npy.arange(0,10)
a[10]

不是这个:

import numpy as npy
a = npy.arange(0,10)
a[1:100]

我可以理解,当我们想要获取数组的一部分时,我们可能并不真正关心索引是否太大(只获取数组中的内容),但这对我来说似乎有点棘手:这很容易也没有注意到您实际上有一个,但是在您计算索引的方式上,没有异常引发。

最佳答案

这与 Python 列表(或一般序列)的行为方式一致:

>>> L = list(range(10))
>>> L[10]
IndexError
...
IndexError: list index out of range
>>> L[1:100]
[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> L[100:100]
[]
  1. 您无法访问不存在的索引。
  2. 但是你可以有一个空范围,即空列表或空 NumPy 数组。因此,如果其中一个索引超出了序列的大小,则取其中的值。

Python tutorial使用更积极的措辞:

However, out of range slice indexes are handled gracefully when used for slicing:

关于python - numpy : indexes too big giving sometimes exceptions, 有时不是,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41872324/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com