Python if 语句:False 与 0.0
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3948877/
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
Python if statement: False vs. 0.0
提问by Izz ad-Din Ruhulessin
Is it possible to:
是否有可能:
for k,v in kwargs.items()
if v == None or v == '' or v == 1.0 or v == False:
del kwargs[k]
without deleting the key if v == 0.0? (False seems to equal 0.0), and without deleting the keys who equal True.
如果 v == 0.0 不删除键?(False 似乎等于 0.0),并且不删除等于 True 的键。
采纳答案by mouad
Or you can put it like this :
或者你可以这样写:
if v in (None, '', 1.0) or v is False:
回答by Mark Byers
You should use v is Falseinstead of v == False. The same applies for your comparison to None. See PEP 8 - Style Guide for Python:
你应该使用v is False而不是v == False. 这同样适用于您与 的比较None。请参阅PEP 8 - Python 风格指南:
Comparisons to singletons like None should always be done with 'is' or 'is not', never the equality operators.
与像 None 这样的单身人士的比较应该总是用“是”或“不是”来完成,而不是等号运算符。
回答by Tony Veijalainen
Slow down guys with your advice, from PEP 8:
根据 PEP 8 的建议放慢速度:
Don't compare boolean values to True or False using ==
Yes: if greeting: No: if greeting == True: Worse: if greeting is True:
不要使用 == 将布尔值与 True 或 False 进行比较
Yes: if greeting: No: if greeting == True: Worse: if greeting is True:
Also comparing float value you should not use ==but
还比较浮点值你不应该使用 ==但是
abs(x-other) < verysmall
abs(x-other) < 非常小
回答by Izz ad-Din Ruhulessin
Thanks for your replies. Using the suggestions, the problem was solved:
感谢您的回复。使用建议,问题解决了:
kwargs = {'None': None, 'empty': '', 'False': False, 'float': 1.0, 'True': True}
for k,v in kwargs.items():
if v in (None, '', 1.0) and v is not True:
del kwargs[k]
if v is False:
del kwargs[k]
kwargs
{'True': True}
-->
-->
kwargs = {'None': None, 'empty': '', 'False': False, 'float': 0.0, 'True': True}
for k,v in kwargs.items():
if v in (None, '', 1.0) and v is not True:
del kwargs[k]
if v is False:
del kwargs[k]
kwargs
{'True': True, 'float': 0.0}
回答by David
Also you could use
你也可以使用
if not v:
# do something
This may not be quite as precise as if v is Falseas it also runs for if vis 0, None, empty setetc.
这可能不是很一样精确的if v is False,因为它也运行了,如果v是0,None,empty set等。
I had trouble with this problem and the above solution worked for me.
我遇到了这个问题,上面的解决方案对我有用。

