a = 6
item_list = [1,2,3,4,5]
for items in item_list:
if items == a:
print("match found")
else:
print ("no match")
在此代码中,我希望“ no match”在完成所有迭代后仅打印一次;并非每次迭代。如何修改代码?
答案 0 :(得分:5)
改为使用:
a = 6
item_list = [1,2,3,4,5]
if a in item_list:
print("match found")
else:
print ("no match")
无需自己迭代列表,请使用内置方法。
答案 1 :(得分:0)
您可以在index
上使用list
或使用in
运算符
In [39]: a = 6
...: item_list = [1,2,3,4,5]
In [40]: try:
...: index = item_list.index(a)
...: print("match found")
...: except:
...: print("no match")
...:
no match
In [41]: if a in item_list:
...: print("match found")
...: else:
...: print("no match")
...:
no match
答案 2 :(得分:0)
a in b
通常是一个更好的解决方案,但是如果要遍历整个列表,可以创建一个变量来存储
匹配并检查for循环到期时是否填充了变量。
a = 6
memory = []
item_list = [1,2,3,4,5]
for items in item_list:
if items == a:
memory.append(a)
print("match found")
if len(memory) == 0:
print("No matches")
a
永远不会出现在循环中,因为您只循环遍历item_list,fyi中的元素
答案 3 :(得分:0)
a = 6
item_list = [1,2,3,4,5]
found_in_list_boolean = False
for items in item_list:
if items == a:
print("match found")
'''Set the boolean to True as you reached the match found statement '''
found_in_list_boolean = True
'''2 ways from here'''
'''First Way : If found_in_list_boolean is true print something and for false print not found'''
if (found_in_list_boolean):
print("Found")
else:
print("not found")
'''Second Way :If found_in_list_boolean is false and print'''
if (found_in_list_boolean==False):
print("not Found")
答案 4 :(得分:0)
正如其他人指出的那样,在这种情况下,最有效的解决方案是使用in
测试,不需要显式循环。
但是,在更普遍的情况下,一个循环一直循环到找到匹配项(如果更复杂的逻辑意味着没有in
的简单等价物),则值得记住一个{{1} }循环可以有一个for
块,如果尚未使用else
退出循环,则该循环将在循环完成后运行。以该代码为例(即使在这种情况下不是必需的),您可以执行以下操作:
break
请注意,如果发现多个匹配项,则此代码与问题代码并不完全相同,因为此处“匹配项找到”仅打印一次,然后通过{{ 1}}。如果您正在寻找可能不止一个的匹配项,例如将它们保存到列表中,那么您将不使用a = 6
item_list = [1,2,3,4,5]
for item in item_list:
if item == a:
print("match found")
break
else:
print ("no match")
和break
,而是在打印之前先测试输出列表是否为空。没有匹配”。
答案 5 :(得分:0)
您可以使用while
循环:
a = 6
item_list = [1, 2, 3, 4, 5]
i = 0
found = False
while True:
i += 1
if item_list[i] == 6:
print("Found")
found = True
if i > len(item_list):
break
if not found:
print("Not found")
请注意,列表中没有6,因此它将print
"Not found"