Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/16.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中搜索数组时如何停止执行else块_Python_Python 3.x_List_Loops_For Loop - Fatal编程技术网

在python中搜索数组时如何停止执行else块

在python中搜索数组时如何停止执行else块,python,python-3.x,list,loops,for-loop,Python,Python 3.x,List,Loops,For Loop,以下是代码部分:- arr=[1,2,3,4,5,6,1,2,3,4,5,6] 我想搜索5并打印它的索引 x=Number to be searched for i in range(len(arr)): if x==arr[i]: print("Found at",i) else: print("Not found") 结果如下:- Found at 4 Found at 10 Not found 用锄头除掉最后一行?不应打印,因为arr中存在5! 注意

以下是代码部分:-

arr=[1,2,3,4,5,6,1,2,3,4,5,6]
我想搜索5并打印它的索引

x=Number to be searched 
for i in range(len(arr)):
    if x==arr[i]:
        print("Found at",i)
else:
    print("Not found")
结果如下:-

Found at 4
Found at 10
Not found
用锄头除掉最后一行?不应打印,因为arr中存在5!
注意:我几天前才开始学习python,所以如果这是一个微不足道的问题,我很抱歉,但我无法找到打印该问题的原因。

您不能在这里使用
else:
,因为
for:…else:
在循环结束时执行
else
分支。您只能通过在
for
循环中使用
break
来防止这种情况,这样它就不会到达终点。您可以
t在此处使用
break`,因为您希望显示所有匹配的值

您有两个选择:

  • 使用标志变量来记住找到的匹配项;当有匹配项时,将其设置为
    True

    found = False  # flag variable, defaulting to 'nothing found'
    for i in range(len(arr)):
        if x==arr[i]:
            print("Found at", i)
            found = True  # found at least one match, set the flag to true
    if not found:
        print("Not found")
    
  • 在打印之前,首先将所有索引收集到一个列表中。如果列表为空,则表示您没有找到任何内容:

    indices = []
    for i in range(len(arr)):
        if x==arr[i]:
            indices.append(i)
    
    if indices:
        for index in indices:
            print('Found at:', index)
    else:
        print("Not found")
    
最后一个选项可以通过单一列表理解和以下内容更简洁地实现:


因此,您似乎不需要
else
部分。啊,我看到我在修复代码以获得正确格式时更改了您的缩进。
else:
循环的
for
分支在到达末尾时执行。您可以使用
break
停止执行
else
分支。但你不能在这里打破这个循环。不要使用
其他:
,请使用标志变量或计数器。如果有人搜索了数组中不存在的项,该怎么办?它应该处理一些错误消息。@Epsilonzero设置一个标志,当您在所需数字上存根时,该标志设置为True。然后,在主for循环之外的条件下,如果标志为False,则打印“未找到”消息。谢谢Brian,这很有效。
indices = [i for i, value in enumerate(arr) if value == x]
if indices:
    for index in indices:
        print("Found at", index)
else:
    print("Not found")