区分 False 和 0 [英] Differentiate False and 0

查看:68
本文介绍了区分 False 和 0的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个包含不同值的列表,如下所示:

Let's say I have a list with different values, like this:

[1,2,3,'b', None, False, True, 7.0]

我想迭代它并检查每个元素是否不在某些禁止值的列表中.例如,这个列表是[0,0.0].

I want to iterate over it and check that every element is not in list of some forbidden values. For example, this list is [0,0.0].

当我检查 [0,0.0] 中是否为 False 时,我得到 True.我知道 python 在这里将 False 转换为 0 - 但是我如何避免它并使此检查正确 - False 值不在 <代码>[0,0.0]?

When I check if False in [0,0.0] I get True. I understand that python casts False to 0 here - but how I can avoid it and make this check right - that False value is not in [0,0.0]?

推荐答案

要区分 False0 可以使用 is来比较它们.False 是一个单例值,总是指向同一个对象.要比较列表中的所有项目以确保它们不是 False,请尝试:

To tell the difference between False and 0 you may use is to compare them. False is a singleton value and always refers to the same object. To compare all the items in a list to make sure they are not False, try:

all(x is not False for x in a_list)

顺便说一句,Python 在这里不进行任何转换:布尔值是整数的子类,False 字面上等于 0,无需转换.

BTW, Python doesn't cast anything here: Booleans are a subclass of integers, and False is literally equal to 0, no conversion required.

这篇关于区分 False 和 0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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