繁体   English   中英

遍历数组从数组中读取 n-1 个元素

[英]Iteration through an array reads n-1 elements from array

我正在尝试从第 5 个元素开始读取数组并存储后续元素。 我的数组长度为 100,所以当我在循环中从 5 开始时,它输出 99。我尝试在循环前后打印结果,循环前输出为 100,循环后输出为 99。

randnums = np.random.randint(1,150, 100) # generating an array
print(len(randnums)) # checking the length before the loop
for i in range(5, randnums.size): # iteration
    test = randnums[:i] # storing the values

print((test.size)) # checking the output: will give 99

为什么我不能存储第 100 个元素?

让我们看看你的循环。 它会在每次迭代时覆盖test ,因此您只需要查看i的最后一个值。

您使用的范围是从5randnums.size == 100 (不包括在内)。 范围在上限上是互斥的。 范围的最后一个元素是99 您可以通过直接打印来检查它(范围是序列):

>>> print(range(5, randnums.size)[-1])
99

因此,您的代码等效于

test = randnums[:99]
print(test.size)

此时的结果应该不会出乎意料。

这些数字实际上是 0 到 99。零是一个实数,并且在数组中占据第一个位置。 因此,您设置了 0-99 no9t 1-100。

那是因为冒号运算符。 [:n] 不包含第 n 个元素。

你可以在这里看到(大约 40:00)它是如何工作的

因此,您希望从原始数组中获取一个大小相同的数组

randnums = np.random.randint(1,150, 100) # generating an array
print(len(randnums)) # checking the length before the loop
for i in range(5, randnums.size + 1): # iteration
    test = randnums[:i] # storing the values

print((test.size)) # checking the output: will give 99

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM