我想知道以下结果将如何产生 True?
>>> x=['0']
>>> valid_diff=['0','1','2','3']
>>> result =any(x for each in x if x in valid_diff)
>>> result
False
我希望结果为 True,因为第一个元素本身将为 True。
任何想法,我确定我在这里遗漏了一些东西..
我想知道以下结果将如何产生 True?
>>> x=['0']
>>> valid_diff=['0','1','2','3']
>>> result =any(x for each in x if x in valid_diff)
>>> result
False
我希望结果为 True,因为第一个元素本身将为 True。
任何想法,我确定我在这里遗漏了一些东西..
你的变量名打错了,你应该检查if each in valid_diff
notif x in valid_diff
和each for each
notx for each
除了错字,我认为这里不需要存储each
,只需使用:
#returns True if any item in x is found in valid_diff
>>> any(each in valid_diff for each in x)
True
或严格坚持您尝试做的事情然后使用它:
any(each in valid_diff and each for each in x)
#will return `True` only if any item found in valid_diff is a Truth value as well.
正确的语法:
>>> result =any(each for each in x if each in valid_diff)