Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python Can';t对整个列表运行while循环_Python_List_While Loop - Fatal编程技术网

Python Can';t对整个列表运行while循环

Python Can';t对整个列表运行while循环,python,list,while-loop,Python,List,While Loop,我不知道如何运行while循环,直到它检查了整个列表 我有这个,但它找到第一个数字后就停止了 numbers = [23,76,45,71,98,23,65,37,93,71,37,21] target = 71 counter = 0 found = False runtime = 0 while runtime < 13: while found == False: if numbers[counter] == target: found = True

我不知道如何运行while循环,直到它检查了整个列表

我有这个,但它找到第一个数字后就停止了

numbers = [23,76,45,71,98,23,65,37,93,71,37,21]
target = 71
counter = 0
found = False
runtime = 0

while runtime < 13:
  while found == False:
    if numbers[counter] == target:
      found = True
    else:
      counter = counter + 1
  runtime = runtime + 1

if found == True:
  print("Found at position" , counter)
else:
  print("No match found")
number=[23,76,45,71,98,23,65,37,93,71,37,21]
目标=71
计数器=0
发现=错误
运行时=0
当运行时间<13时:
当发现==False时:
如果数字[计数器]==目标:
找到=真
其他:
计数器=计数器+1
运行时=运行时+1
如果找到==True:
打印(“在位置处找到”,计数器)
其他:
打印(“未找到匹配项”)

我想让代码显示在位置3和位置9

Try(使用函数)

输出

Found at position 3
Found at position 9

要查找位置,请使用:

p =[i for i, j in enumerate(numbers) if j == target]

然后进行必要的打印。

代码应该做什么-请解释我希望代码显示在位置3处找到,在位置9处找到,但现在它只是说在位置3处找到您的外部循环(
,而运行时<13
)正在继续迭代。但是,由于您在第一次遇到
numbers
中的
target
时声明
found=True
,您的内部循环将不会执行(因为它是由
定义的,而find=False
。我建议在enumerate(numbers)中为I,n考虑类似
的内容
-如果您打算使用循环来解决此问题,请参见-如果n==target或类似内容,请参见-旁边的一个简单的
。无论您将
found
设置为
True
,您的代码只会在循环外检查一次值。因此,它当然只能打印一个“found”消息。我需要它来输出在位置3找到的在位置9找到的。非常感谢!@mrKrauklis确保您理解索引函数以及引发ValueError异常的原因。请查看其他答案。
p =[i for i, j in enumerate(numbers) if j == target]