【问题标题】:Python for loop ignoring if statement [duplicate]Python for循环忽略if语句[重复]
【发布时间】:2017-04-29 12:16:45
【问题描述】:

由于某种原因,python 忽略了我的 if 语句,即使 str(search) 在我的列表 lista 中,它仍然会打印 elif 语句。

我做错了吗?

search = input("what would you like to search for?:")
    for n in range(len(lista)):
         if str(search) in lista[n]:
             print(lista[n])
         elif str(search) not in lista[n]:
             print("search not found in list")
             break 

【问题讨论】:

  • 你为什么使用elif 而不仅仅是else
  • 这是 lista 中的内容,如果我删除 elif 语句,它可以工作,但我想让它在未找到时通知用户,即使我也使用 else,它也会完全相同。

标签: python python-3.x for-loop if-statement


【解决方案1】:

如果search 没有在第一个位置(因为ifelif 是为列表中的每个项目执行)。在您的情况下,您可以简单地使用“触发器”来指示至少一个发现并在循环后执行 if

found = False
for n in range(len(lista)):
     if str(search) in lista[n]:
         print(lista[n])
         found = True
if not found:
     print("search not found in list")

但更好的是直接迭代列表而不是长度范围:

found = False
for item in lista:
     if str(search) in item:
         print(item)
         found = True
if not found:
     print("search not found in list")

如果您不喜欢触发器,您还可以使用条件推导来获取所有匹配项,并将匹配项的数量用作间接触发器:

findings = [item for item in lista if str(search) in item]
if findings:  # you got matches:
    for match in findings:
        print(match)
else:         # no matches
     print("search not found in list")

【讨论】:

  • 谢谢,第一组代码完美运行。我选择了第一个,因为 lista 是一个列表列表。
  • @czedarts 他们都应该做同样的事情,即使它是一个列表。但我很高兴它奏效了。如果它解决了您的问题,请不要忘记accept答案。 :)
  • 关于“如果你不喜欢触发器”,flag 变量可以很容易地替换为 for-else 构造,前提是使用 break 来摆脱 for找到东西就循环。
  • @blubberdiblub 据我了解代码的目的:它应该打印所有匹配项。在这种情况下,break 不是一个好的选择,然后你就不能使用else
  • @MSeifert 是的,确实,这阻止了爆发。
猜你喜欢
  • 2019-10-22
  • 1970-01-01
  • 1970-01-01
  • 2020-03-05
  • 1970-01-01
  • 1970-01-01
  • 2020-10-28
  • 2015-08-13
  • 1970-01-01
相关资源
最近更新 更多