Python 中 bool() 的实际应用是什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24868086/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 05:21:46  来源:igfitidea点击:

What is the practical application of bool() in Python?

pythonpython-2.7boolean

提问by Muhamed Huseinba?i?

When it is being used in everyday coding? I am learning Python using this tutorial. What am I referring to is described here(middle of the page), but I can't get it. I understand the principles of using True and False, but I don't get when (or do) we actually use the bool()function in practice while writing our code. It would help me if you give the everyday, practical example of bool()in code.

什么时候用于日常编码?我正在使用本教程学习 Python 。我指的是这里(页面中间)描述的内容,但我无法理解。我了解使用 True 和 False 的原则,但我不知道我们何时(或何时)bool()在编写代码时在实践中实际使用该函数。如果您提供bool()代码中的日常实用示例,它将对我有所帮助。

采纳答案by Martijn Pieters

It lets you convert any Python value to a boolean value.

它允许您将任何 Python 值转换为布尔值。

Sometimes you want to store either Trueor Falsedepending on another Python object. Instead of:

有时您想存储TrueFalse依赖另一个 Python 对象。代替:

if python_object:
    result = True
else:
    result = False

you simply do:

你只需要做:

result = bool(python_object)

HowPython objects are converted to a boolean value, all depends on their truth value. Generally speaking, None, numeric 0 and empty containers (empty list, dictionary, set, tuple, string, etc.) are all False, the rest is True.

Python 对象如何转换为布尔值,完全取决于它们的真值。一般来说None,数字0和空容器(空列表、字典、集合、元组、字符串等)都是False,其余的是True

You use it whenever you need an explicit boolean value. Say you are building an object tree, and you want to include a method that returns Trueif there are children in the tree:

每当您需要明确的布尔值时,您就可以使用它。假设您正在构建一个对象树,并且您希望包含一个方法,该方法True在树中有子项时返回:

class Tree(object):
    def __init__(self, children):
        self.children

    def has_children(self):
        return bool(self.children)

Now Tree().has_children()will return Truewhen self.childrenis not empty, Falseotherwise.

现在不为空时Tree().has_children()返回,否则返回。Trueself.childrenFalse

回答by Lee Watson

Converts a value to a boolean.

将值转换为布尔值。

回答by Martijn Pieters

boolexposes the fact that Python allows for boolean conversions to things that you wouldn't typically consider to be True or False.

bool揭示了 Python 允许将布尔值转换为您通常不会认为是 True 或 False 的事情的事实。

An example of this is lists. If len(my_list)would be greater than 0, it also treats this as True. If it has no length -- if len()would return 0 -- it is False. This lets you write code like this:

这方面的一个例子是列表。如果len(my_list)大于 0,它也将其视为True。如果它没有长度——如果len()会返回 0——它是False. 这使您可以编写如下代码:

def check_list_for_values(my_list, value):
    return [x for x in my_list if x == value]

your_list = [5, 6, 7, 8, 9, 5, 3, 4, 8]
if check_list_for_values(3, your_list):
    print "got a match"

If check_list_for_valuesreturns a list that has length greater than 0, then it prints "got a match" because it evaluates to True. If there is no length to the list that would be returned...

如果check_list_for_values返回长度大于 0 的列表,则它会打印“got a match”,因为它的计算结果为True。如果返回的列表没有长度......

your_list = [5, 6, 7, 8, 9, 5, 3, 4, 8]
if check_list_for_values('elephant', your_list):
    print "got a match"

Then there will be nothing printed, because it evaluates to False.

然后将不会打印任何内容,因为它的计算结果为False

回答by mgoldwasser

To understand what bool()does we need to first understand the concept of a boolean.

要了解什么bool(),我们首先需要了解布尔值的概念。

A boolean variable is represented by either a 0 or 1 in binary in most programming languages. A 1 represents a "True" and a 0 represents a "False"

在大多数编程语言中,布尔变量由二进制的 0 或 1 表示。1 代表“真”,0 代表“假”

The number 1 is different from a boolean value of True in some respects. For example, take the following code:

数字 1 在某些方面不同于布尔值 True。例如,采用以下代码:

>>> 1 is True
False

Notice that 1 is different than True according to Python. However:

请注意,根据 Python,1 与 True 不同。然而:

>>> bool(1) is True
True

When we use the bool()function here, we convert 1 to a boolean. This conversion is called "casting". Casting 1 to boolean returns the value of "True".

当我们在bool()这里使用该函数时,我们将 1 转换为布尔值。这种转换称为“铸造”。将 1 转换为 boolean 会返回“True”的值。

Most objects can be cast to a boolean value. From my experience, you should expect every standard object to evaluate to True unless it is 0, None, False or an empty iterable (for example: "", [], or {}). So as an example:

大多数对象都可以转换为布尔值。根据我的经验,您应该期望每个标准对象都评估为 True,除非它是 0、None、False 或空的可迭代对象(例如:“”、[] 或 {})。举个例子:

>>> bool({})
False
>>> bool({"":False})
True
>>> bool(None)
False
>>> bool("")
False
>>> bool("hello")
True
>>> bool(500)
True
>>> bool(0)
False
>>> bool(False)
False
>>> bool(-1)
True

Lastly, a boolean prints as either "True" or "False"

最后,布尔值打印为“真”或“假”

>>> print bool(1)
True