为什么从字符串转换的python float与具有相同值的普通float相同?

jls*_*est 4 python

我在Python 3.6.5中遇到了一个奇怪的现象:虽然它们彼此相等但float('50.0')不一样.float(50.0)

我运行了一些代码来找到差异.除了python说他们不一样,我找不到区别.我很困惑.如果有人能解释这里发生的事情,我会喜欢它.

这是我的测试:

if float('50.0') is float(50.0):
    print("float('50.0') is float(50.0)")
else:
    print("float('50.0') is not float(50.0)")

if float('50.0') == float(50.0):
    print("float('50.0') == float(50.0)")
else:
    print("float('50.0') != float(50.0)")

if float('50.0') is 50.0:
    print("float('50.0') is 50.0")
else:
    print("float('50.0') is not 50.0")

if float(50.0) is 50.0:
    print('float(50.0) is 50.0')
else:
    print('float(50.0) is not 50.0')

if float(50.0) is float(50.0):
    print('float(50.0) is float(50.0)')
else:
    print('float(50.0) is not float(50.0)')

xstr_float = float('50.0')
norm_float = float(50.0)
print ('xstr_float: {0:.100f}'.format(xstr_float))
print ('xstr_float is of type:{}'.format(type(xstr_float)))
print ('norm_float: {0:.100f}'.format(norm_float))
print ('norm_float is of type:{}'.format(type(norm_float)))
Run Code Online (Sandbox Code Playgroud)

和我的结果:

float('50.0') is not float(50.0)
float('50.0') == float(50.0)
float('50.0') is not 50.0
float(50.0) is 50.0
float(50.0) is float(50.0)
xstr_float: 50.0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
xstr_float is of type:<class 'float'>
norm_float: 50.0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
norm_float is of type:<class 'float'>
Run Code Online (Sandbox Code Playgroud)

基于评论中的一些讨论,我尝试了以下内容,得到的结果不回答问题:

x = float(50.0)
y = float(50.0)
if x is y:
    print('x is y')
else:
    print('x is not y')

x=12345
y=12345
if x is y:
    print('x is y')
else:
    print('x is not y')
Run Code Online (Sandbox Code Playgroud)

结果是:

x is y
x is y
Run Code Online (Sandbox Code Playgroud)

更新:我已经标记了一个正确的答案,根据对该答案的评论,我想向其他人展示可能会让我感到困惑的是:

当python创建一个对象时,它会被分配一个ID.is比较两个对象时返回true,返回相同的ID.有时候python会缓存并重用一个对象.因此,在x is y我们可以看到给出并重用对象的情况下,因为ID是相同的.我们还看到python会话之间的ID发生了变化:

x=12345
y=12345
if x is y:
    print('x is y')
else:
    print('x is not y')
print('x_id: {}'.format(id(x)))
print('y_id: {}'.format(id(y)))
Run Code Online (Sandbox Code Playgroud)

结果是

x is y
x_id: 2476500365040
y_id: 2476500365040
Run Code Online (Sandbox Code Playgroud)

并在下一次运行中导致

x is y
x_id: 2234418638576
y_id: 2234418638576
Run Code Online (Sandbox Code Playgroud)

如果由于任何原因无法重用相同的对象来表示x和y,则x is y返回false.

Dor*_*ora 5

我想你可能会对一开始就困惑我的事情感到困惑.is不同于==.

isTrue如果两个变量指向同一个对象,则返回.

==True如果变量指向相等的对象,则返回.

帮助我理解这个问题的答案是在这个问题下: Python Python 之间有区别吗?==is

  • 为理解添加一点.`x是y`与`id(x)== id(y)`具有相同的含义. (2认同)