使用 'while' 函数在随机生成的范围内查找数字的索引

Finding the index of a number using a 'while' function in a randomly generated range

我的作业题目是:

  1. 从两行代码开始:
import numpy as np
x = np.random.rand(10_000) #this generates 10,000 random numbers from a uniform distribution over [0,1)

现在,编写一个循环来查找 x 中第一个大于 0.999 的值的索引。找到后停止循环。

  1. 做与 1 相同的练习,但改用 while 循环。

对于第 1 个,我写了这个并且有效:

for i, num in enumerate(x):
    if num > 0.999:
        print(i)
        break

对于数字 2,我一直无法弄清楚。 有人知道怎么做吗?

使用 while 循环,只需创建一个变量,您可以在每次迭代中递增该变量,以便在满足 while 循环的条件后找到 x 变量的索引。

import numpy as np
x = np.random.rand(10_000)

#For loop
for i, num in enumerate(x):
    if num > 0.999:
        print(i)
        break

#While loop
i = 0
while x[i] < 0.999:
    i += 1
print(i)