使用不检查是否为真
Using not to check if True
我刚刚完成了我要解决的问题的一个非常简化的版本:
test = [False]
for element in test:
if value not False:
return True
这是为了检查一个元素是否在列表中 True
。然而,这个 returns 第 3 行的 SyntaxError
您似乎想要遍历布尔值列表,并且 return True 一旦找到一个 True 值?如果是这样,您需要测试元素,而不是列表:
test = [False]
for element in test:
if element not False:
return True
那是因为
value not False
不是有效的 Python 语法。你可能想要
value is not False
另一个问题是您想要 element
而不是 value
。
存在语法错误,因为 if value not False
没有意义。您要检查 if value is not False
:
test = [False]
for element in test:
if element is not False:
return True
Python 具有内置的 any
函数,该函数检查序列中每个元素的 True
-ness 直到找到一个:
>>> any([False, False, False, True, False]
True
linked documentation 处的代码与您的非常相似:
def any(iterable):
for element in iterable:
if element:
return True
return False
我刚刚完成了我要解决的问题的一个非常简化的版本:
test = [False]
for element in test:
if value not False:
return True
这是为了检查一个元素是否在列表中 True
。然而,这个 returns 第 3 行的 SyntaxError
您似乎想要遍历布尔值列表,并且 return True 一旦找到一个 True 值?如果是这样,您需要测试元素,而不是列表:
test = [False]
for element in test:
if element not False:
return True
那是因为
value not False
不是有效的 Python 语法。你可能想要
value is not False
另一个问题是您想要 element
而不是 value
。
存在语法错误,因为 if value not False
没有意义。您要检查 if value is not False
:
test = [False]
for element in test:
if element is not False:
return True
Python 具有内置的 any
函数,该函数检查序列中每个元素的 True
-ness 直到找到一个:
>>> any([False, False, False, True, False]
True
linked documentation 处的代码与您的非常相似:
def any(iterable):
for element in iterable:
if element:
return True
return False