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-列表搜索重复不匹配?_Python_List_Sorting_Python 2.7_Search - Fatal编程技术网

Python-列表搜索重复不匹配?

Python-列表搜索重复不匹配?,python,list,sorting,python-2.7,search,Python,List,Sorting,Python 2.7,Search,在这个python程序中,我试图实现排序列表中的搜索 我面临的问题很简单,但我无法解决它。我想打印元素,当元素被找到时,当它没有找到时,我想打印“不匹配”。但问题是,如果所选元素==sorted_list[i],它会打印“不匹配”的每个元素。我不想得到这个。如果我要查找的元素不在列表中,我希望获得一次“不匹配” 这是代码 for i in range(0, len(sorted_list)): if take_input == sorted_list[i]: print

在这个python程序中,我试图实现排序列表中的搜索

我面临的问题很简单,但我无法解决它。我想打印元素,当元素被找到时,当它没有找到时,我想打印“不匹配”。但问题是,如果所选元素==sorted_list[i],它会打印“不匹配”的每个元素。我不想得到这个。如果我要查找的元素不在列表中,我希望获得一次“不匹配”

这是代码

for i in range(0, len(sorted_list)):
    if take_input == sorted_list[i]:
        print sorted_list[i]
    elif take_input != sorted_list[i]:
        print "Not Matched"

您可以将
用于。。。否则…
带有
break
语句:

for i in range(0, len(sorted_list)):
    if take_input == sorted_list[i]:
        print sorted_list[i]
        break  # get out of the for loop.
else:
    # This will be executed only if the `for` loop is not terminated with `break`.
    print "Not Matched"
如果使用,则无需迭代:

if take_input in sorted_list:
    print take_input
else:
    print "Not Matched"

顺便说一句,如果不需要索引,只需迭代序列即可。

使用中的
检查
获取输入
是否在
排序列表
中,避免迭代
排序列表

if take_input in sorted_list:
    print take_input
else:
    print "Not Matched"
您不需要使用范围来迭代排序列表
,您只需使用:

for  i in sorted_list:
    if  i == take_input
如果需要索引,应使用
枚举

for ind, ele in enumerate(sorted_list): # ind is each index, ele each each element in the list
    if take_input == sorted_list[ind]:
它可以这样工作。(开关)


这将确保只打印一次找到的元素。如果开关未设置为1,则表示元素不存在,并且将打印“不匹配”(一次)。

您知道排序列表中项目的
?如果在分拣机列表中输入:
switch_found = 0

for i in range(0, len(sorted_list)):
    if take_input == sorted_list[i]:
        switch_found = 1
        break
# else it will continue 

if switch_found == 1:
    print sorted_list[i]
else:
    print "Not Matched"