is
和==
的区别?¶我们一共讨论3个字符格式
str
list
pd.DataFrame
a = "Hello world!"
b = "Hello world!"
print type(a)
print a is b
print a == b
a = [1,2,3]
b = [1,2,3]
print type(a)
print a is b
print a == b
import pandas as pd
a = pd.DataFrame({"x": [1,2,3]})
b = pd.DataFrame({"x": [1,2,3]})
print type(a)
print a is b
print a == b
我们发现a == b
都是True
,但是a is b
都是False
。
我们再看一组例子。
a = "Hello world!"
b = a
print type(a)
print a is b
print a == b
a = [1,2,3]
b = a
print type(a)
print a is b
print a == b
a = pd.DataFrame({"x": [1,2,3]})
b = a
print type(a)
print a is b
print a == b
我们发现直接将b = a
后,a is b
才会True
。
这里的区别是,
a is b
$\to$id(a) == id(b)
$\to$ a
和b
相同
a == b
$\to$a.__eq(b)__
$\to$ a
和b
相等而已
a = "Hello world!"
b = "Hello world!"
print type(a)
print a is b
print a == b
print id(a) == id(b)
print id(a)
print id(b)
a = [1,2,3]
b = [1,2,3]
print type(a)
print a is b
print a == b
print id(a) == id(b)
print id(a)
print id(b)
a = pd.DataFrame({"x": [1,2,3]})
b = pd.DataFrame({"x": [1,2,3]})
print type(a)
print a is b
print a == b
print id(a) == id(b)
print id(a)
print id(b)
这里我们会发现,虽然相等,但是相同的原因是,a
和b
的内存地址不同。
但是这里有一个意外,
a = "Hello"
b = "Hello"
print type(a)
print a is b
print a == b
print id(a) == id(b)
print id(a)
print id(b)
当处理单一字符串的时候,a
和b
会共用一个内存地址,因此这也是python快捷的原因之一。