布尔测试在Python列表 [英] Boolean testing a list in Python

查看:157
本文介绍了布尔测试在Python列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是测试列表,看它是否是空的或没有。通常我用LEN(名单)== 0,我依稀记得读一会儿前,要检验的正确方法,如果列表是空的是它是否是真还是假。

I was testing a list to see if it's empty or not. Normally I use len(list) == 0 and I vaguely remembered reading a little while ago that the correct way to test if a list is empty was whether it was True or false.

所以,我试图名单假的,那返回false。也许我猜想使用==?
不,也返回false。名单是真实的,还给象清单作虚伪==真。

So I tried list is False, and that returned False. Maybe I'm suppose to be using == ? Nope, that also returned false. list is True, returned false as did list == True.

现在我很困惑,所以我做了快速谷歌,并在最后:<一href=\"http://stackoverflow.com/questions/53513/python-what-is-the-best-way-to-check-if-a-list-is-empty\">Python:什么是检查一个列表为空最好的方法是什么?

Now I'm confused so I do a quick google and end up at: Python: What is the best way to check if a list is empty?

顶答案是:

if not a:
    print "List is empty"

于是,我四处搜寻一些和蟒蛇人工结束,其中4.1状态:

So I search around some more and end up in the python manual where 4.1 states:

任何对象都可以为真值进行测试,在if或while条件或下面的布尔运算的操作使用。以下值被认为是假的:

Any object can be tested for truth value, for use in an if or while condition or as operand of the Boolean operations below. The following values are considered false:

任何空序列,例如,'',(),[]

any empty sequence, for example, '', (), [].

现在我平淡困惑。如果我的测试,如果没有列出一个列表,它工作正常。但是,如果一个空表是假的,那么为什么我不能只是做,如果名单是假,或者如果列表==假?

Now I'm plain confused. If I test a list as if not list, it works fine. But if an empty list is false, then why can't I just do if list is False or if list == False?

感谢

推荐答案

这是空列表是不假,但是当你把它转换成一个布尔值,将其转换为False。同样,对于类型的字典,元组,字符串等。

An empty list is not False, but when you convert it to a boolean, it converts to False. Likewise for dicts, tuples, strings, etc.:

>>> [] == False
False
>>> bool([]) == False
True
>>> {} == False
False
>>> bool({}) == False
True

当你把东西在如果条款的情况下,它是用于测试如果。这就是为什么如果someList 相同如果布尔(someList)。同样,不是foo 做了布尔没有,所以不是[] 等于true。

When you put something in the condition of an if clause, it is its boolean value that is used for testing the if. That's why if someList is the same as if bool(someList). Likewise, not foo does a boolean not, so not [] equals True.

这篇关于布尔测试在Python列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆