繁体   English   中英

尽管触发了适当的 boolean 值,但如果语句不起作用 | Python

[英]If statement not working despite having triggered the appropriate boolean value | Python

我想在good_view_listTrue时执行这个 if 语句,我知道它是一个列表,但是每当我打印出它的 boolean 它给我一个True值(我假设因为里面有字符串),为什么不if good_view_time is True: good_view_time True if 语句有效。

我知道其他选择,只是想知道为什么这个不起作用。

good_view_time = ['https://www.instagram.com/p/CKmTcvmHYkY/', 'https://www.instagram.com/p/CKcOxtlHJsy/' , 'https://www.instagram.com/p/CKpHBAcHkhl/']

#returns True
print(bool(good_view_time))

if good_view_time is True:
    for post in good_view_time:

        print(post)

bool(good_view_time)返回True ,但good_view_time本身是一个列表,它不能是字面上True good_view_time不是True ,但将其转换为 Boolean 会给出 True ,因为非空列表是真实的。 同样, bool("Hello") is True ,但字符串"Hello"本身绝对不等于 True (为什么会这样?它是一个字符串,), is完全等同于True运营商会检查。

所以,你应该比较:

if bool(good_view_time) is True:

或者,这是等效的:

if good_view_time:

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM