[英]Execution for-loop in Python
def search_for_element(L, char):
for i in L:
if i == char:
return True
else:
return False
When I run the function, it only outputs one statement on the screen.当我运行该函数时,它只在屏幕上输出一个语句。 So why is the for loop only executed once?
那么为什么for循环只执行一次呢?
return
terminates the function, move return False
to after the loop: return
终止函数,将return False
移到循环之后:
def search_for_element(L, char):
for i in L:
if i == char:
return True
return False
Or simply:或者干脆:
def search_for_element(L, char):
return char in L
Although note the latter is not exactly equivalent, since it also tests identity (not just equality).尽管请注意后者并不完全等效,因为它也测试身份(不仅仅是相等性)。 This will only matter in rather unusual circumstance though, for example
numpy.NAN == numpy.NAN
is False
but numpy.NAN in [numpy.NAN]
is True
.这只会在相当不寻常的情况下很重要,例如
numpy.NAN == numpy.NAN
是False
但numpy.NAN in [numpy.NAN]
是True
。
So the one-liner alternative would be:所以单线替代方案是:
def search_for_element(L, char):
return any(char == i for i in L)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.