【问题标题】:Weird Behvaiour of is operator pythonis operator python的奇怪行为
【发布时间】:2020-06-22 04:53:38
【问题描述】:

如果我执行以下操作

x = 0
y = 0
print(x is y)

我收到True

以下代码

x = 0
y = 0.0
print(x is y)

输出False,这是预期的行为。

但是

x = 0.0
y = 0.0
print(x is y)

返回False。为什么会发生这种情况以及如何解决?

我的用例是我需要将 0 和 0.0 与 python 中的其他值区分开来,例如 False、"" 等,它们会在 x==0 比较中返回 True

编辑:

cmets 中的链接问题没有回答我的问题。我需要知道如何解决这个问题。

【问题讨论】:

标签: python-3.x


【解决方案1】:

您可以先检查type,然后再检查这种情况下的值。

类似这样的:

>>> a = 0
>>> b = 0
>>> c = 0.0
>>> d = 0.0
>>> type(a) is type(b) and a == b
True
>>> type(a) is type(c) and a == c
False
>>> type(c) is type(d) and c == d
True
>>>

【讨论】:

    猜你喜欢
    • 2020-08-01
    • 2010-10-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-22
    • 2013-04-01
    相关资源
    最近更新 更多