检查 False 的正确方法是什么?

2023-09-01Python开发问题
2

本文介绍了检查 False 的正确方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

哪个更好?(为什么?)

Which is better? (and why?)

if somevalue == False:

if somevalue is False:

如果 somevalue 是字符串,你的答案会改变吗?

Does your answer change if somevalue is a string?

推荐答案

这取决于 somevalue 可以是什么:如果 somevalue 可以是任何你可以检查它的东西一个布尔值和 not:

It rather depends on what somevalue can be: if somevalue could be anything you could check that it's a boolean and not:

if isinstance(somevalue, bool) and not somevalue

这不依赖于 False 是单例.如果它总是一个单例,你也可以这样做:

this doesn't rely on False being a singleton. If it always is a singleton you can also do:

if somevalue is False

<小时>

但是 Python 的 PEP8 声明你不应该关心它是否与类有关,只需使用:


But PEP8 of Python states you shouldn't care if it about the class and just use:

if not somevalue

这将评估 somevalue 是否为假".请参阅 关于真值测试的 Python 文档.

this will evaluate if somevalue is "falsy". See Python documentation on Truth value testing.

PEP8 状态:

不要使用 == 将布尔值与 True 或 False 进行比较.

Don't compare boolean values to True or False using == .

并给出这些例子:

Yes:   if greeting:
No:    if greeting == True:
Worse: if greeting is True:

在您的情况下翻译为:

Yes:   if not greeting:
No:    if greeting == False:
Worse: if greeting is False:

请记住,除了空字符串 '' 之外,每个字符串都被认为是真实的".

Keep in mind that each string is considered "truthy" except the empty string ''.

这篇关于检查 False 的正确方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

在xarray中按单个维度的多个坐标分组
groupby multiple coords along a single dimension in xarray(在xarray中按单个维度的多个坐标分组)...
2024-08-22 Python开发问题
15

Pandas中的GROUP BY AND SUM不丢失列
Group by and Sum in Pandas without losing columns(Pandas中的GROUP BY AND SUM不丢失列)...
2024-08-22 Python开发问题
17

GROUP BY+新列+基于条件的前一行抓取值
Group by + New Column + Grab value former row based on conditionals(GROUP BY+新列+基于条件的前一行抓取值)...
2024-08-22 Python开发问题
18

PANDA中的Groupby算法和插值算法
Groupby and interpolate in Pandas(PANDA中的Groupby算法和插值算法)...
2024-08-22 Python开发问题
11

PANAS-基于列对行进行分组,并将NaN替换为非空值
Pandas - Group Rows based on a column and replace NaN with non-null values(PANAS-基于列对行进行分组,并将NaN替换为非空值)...
2024-08-22 Python开发问题
10

按10分钟间隔对 pandas 数据帧进行分组
Grouping pandas DataFrame by 10 minute intervals(按10分钟间隔对 pandas 数据帧进行分组)...
2024-08-22 Python开发问题
11