简体   繁体   English

为什么在Python中的while循环中空列表的计算结果为False

[英]Why does an empty list evaluates to False on a while loop in Python

What is process that occurs for a while-loop to evaluate to False on an empty list ? 在空列表中,while循环计算为False过程是什么?

For instance: 例如:

a=[1, 2, 3]
while a:
    a.pop()

Essentially, I want to know which method or attribute of the list object the while -loop is inspecting in order to decide wether to terminate or not. 从本质上讲,我想知道哪种方法或列表属性对象的while -loop是为了据此决定是否终止或不检查。

Loops and conditionals implicitly use bool on all their conditions. 循环和条件隐式在所有条件下使用bool The procedure is documented explicitly in the "Truth Value Testing" section of the docs. 该过程在文档的“真值测试”部分中明确记录。 For a sequence like a list, this usually ends up being a check of the __len__ method. 对于像列表这样的序列,这通常最终会检查__len__方法。

bool works like this: first it tries the __bool__ method. bool工作方式如下:首先尝试__bool__方法。 If __bool__ is not implemented, it checks if __len__ is nonzero, and if that isn't possible, just returns True . 如果没有实现__bool__ ,它会检查__len__是否为非零,如果不可能,则返回True

As with all magic method lookup, Python will only look at the class, never the instance (see Special method lookup ). 与所有魔术方法查找一样,Python只会查看类,而不是实例(请参阅特殊方法查找 )。 If your question is about how to change the behavior, you will need to subclass. 如果您的问题是关于如何更改行为,则需要子类化。 Assigning a single replacement method to an instance dictionary won't work at all. 将单个替换方法分配给实例字典根本不起作用。

Great question! 好问题! It's inspecting bool(a) , which (usually) calls type(a).__bool__(a) . 它正在检查bool(a) ,它(通常)调用type(a).__bool__(a)

Python implements certain things using "magic methods". Python使用“魔术方法”实现某些功能。 Basically, if you've got a data type defined like so: 基本上,如果你有一个如此定义的数据类型:

class MyExampleDataType:
    def __init__(self, val):
        self.val = val

    def __bool__(self):
        return self.val > 20

Then this code will do what it looks like it'll do: 然后这段代码将执行它看起来会做的事情:

a = MyExampleDataType(5)
b = MyExampleDataType(30)

if a:
    print("Won't print; 5 < 20")
if b:
    print("Will print; 30 > 20")

For more information, see the Python Documentation: 3.3 Special Method Names . 有关更多信息,请参阅Python文档: 3.3特殊方法名称

A condition like if my_var is equivalent to if bool(my_var) and this page explains it rather nicely: 一个条件, if my_var等于if bool(my_var)这个页面很好地解释了它:

Return Value from bool() bool的返回值()

The bool() returns: bool()返回:

False if the value is omitted or false True if the value is true 如果省略该值,则返回false;如果值为true,则返回false

The following values are considered false in Python: 在Python中,以下值被视为false:

None 没有

False

Zero of any numeric type. 任何数字类型的零。 For example, 0, 0.0, 0j 例如,0,0.0,0j

Empty sequence. 空序列。 For example, (), [], ''. 例如, (), [], ''。

Empty mapping. 空映射。 For example, {} 例如, {}

objects of Classes which has bool () or len() method which returns 0 or False 具有bool ()或len()方法的类的对象,返回0或False

All other values except these values are considered true. 除这些值之外的所有其他值都被视为真。

You can check whether a list is empty by using the bool() function. 您可以使用bool()函数检查列表是否为空。 It evaluates to False if the variable doesn't exist or in the case of a list, when it is empty. 如果变量不存在,则计算结果为False;如果变量为空,则计算结果为空。

In your case you could do this: 在你的情况下,你可以这样做:

a=[1,2,3]

while bool(a) is True:
    a.pop()

Or even easier: 甚至更容易:

a = [1,2,3]

while len(a) > 0:

    print(a.pop())

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

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