无法为整个列表运行 while 循环



在检查完整个列表之前,我不确定如何运行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")

我希望代码显示在位置3找到和在位置9找到

尝试(使用index((函数(

numbers = [23,76,45,71,98,23,65,37,93,71,37,21]
offset = 0
while True:
try:
idx = numbers.index(71,offset)
print(f'Found at position {idx}')
offset = idx + 1
except ValueError:
break

输出

Found at position 3
Found at position 9

要查找位置,请使用:

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

然后进行必要的打印。

最新更新