空列表布尔值 [英] Empty list boolean value

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

问题描述

这可能只是白痴,但对我来说有点混乱:

This may be simply idiotic, but for me it's a bit confusing:

In [697]: l=[]

In [698]: bool(l)
Out[698]: False

In [699]: l == True
Out[699]: False

In [700]: l == False
Out[700]: False 

In [701]: False == False
Out[701]: True

为什么l==False返回FalseFalse == False返回True?

推荐答案

您正在根据布尔值False的文字值对其进行检查.与'A' == False相同的是错误的.

You are checking it against the literal value of the boolean False. The same as 'A' == False will not be true.

如果投射它,您会看到不同之处:

If you cast it, you'll see the difference:

>>> l = []
>>> l is True
False
>>> l is False
False
>>> l == True
False
>>> l == False
False
>>> bool(l) == False
True

False == False为true的原因是因为您正在比较相同的对象.与2 == 2'A' == 'A'相同.

The reason False == False is true is because you are comparing the same objects. It is the same as 2 == 2 or 'A' == 'A'.

当您看到诸如if l:之类的东西并且此检查从未通过时,困难就来了.那是因为您要检查项目的真值.按照惯例,所有这些项目都将通过布尔检查失败-也就是说,它们的布尔值将为False:

The difficulty comes when you see things like if l: and this check never passes. That is because you are checking against the truth value of the item. By convention, all these items will fail a boolean check - that is, their boolean value will be False:

  • None
  • False(显然)
  • 任何空序列:''[]()
  • 任何零"值:00.0
  • 任何空集合:{}(空字典)
  • len()返回0
  • 的任何内容
  • None
  • False (obviously)
  • Any empty sequence: '', [], ()
  • Any "zero" value: 0, 0.0, etc.
  • Any empty collection: {} (an empty dict)
  • Anything whose len() returns a 0

这些称为假"值. 其他所有内容均为"true" .可能会导致一些奇怪的事情,例如:

These are called "falsey" values. Everything else is "true". Which can lead to some strange things like:

>>> def foo():
...   pass
...
>>> bool(foo)
True

在这里还需要注意的是,不返回显式值的方法始终将None作为其返回类型,从而导致以下情况:

It is also good to note here that methods that don't return an explicit value, always have None as their return type, which leads to this:

>>> def bar():
...   x = 1+1
...
>>> bool(bar)
True
>>> bool(bar())
False

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

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