gpt4 book ai didi

Python 在遍历列表时找不到值

转载 作者:太空宇宙 更新时间:2023-11-04 06:46:44 26 4
gpt4 key购买 nike

我有一个 while 循环,它遍历一个列表,试图找到数字 1。我有下面的代码,它“几乎”遍历了所有列表,但它没有找到值 1 的索引

numbers = [24, 10, 92, 28, 71, 1, 80, 70]
counter = 0
number_to_find = 1

def my_loop():
global counter
while counter > 6: #Also not sure while 7 doesn't work, says out of range?
if numbers[counter] == number_to_find:
print "Number found at position", counter

else:
print "Counter not found in position" , counter
counter = counter + 1
my_loop()


print my_loop()

最佳答案

这是一段非常困惑的代码。

  1. 打印 输出,但该函数不返回任何内容。 (它也打印东西,但不返回任何东西。)
  2. 该函数有一个while 循环,并且还对自身进行递归。 (在某些情况下这是合适的,但这不是其中之一。)
  3. counter 最初为 0,但您的第一个检查是 counter > 6。 0 不大于 6。 (这在技术上并没有错,但非常令人困惑。)
  4. 1 位于索引 5。为什么要查找 6?
  5. 一旦达到所需的索引,就不会终止循环。

关于Python 在遍历列表时找不到值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34729118/

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