gpt4 book ai didi

python - "=="和 "is"之间有区别吗?

转载 作者:太空宇宙 更新时间:2023-11-03 21:33:59 24 4
gpt4 key购买 nike

我的Google-fu让我失望了。

在 Python 中,以下两个相等性测试等效吗?

n = 5
# Test one.
if n == 5:
print 'Yay!'

# Test two.
if n is 5:
print 'Yay!'

这对于您要比较实例的对象(例如list)是否成立?

好的,这回答了我的问题:

L = []
L.append(1)
if L == [1]:
print 'Yay!'
# Holds true, but...

if L is [1]:
print 'Yay!'
# Doesn't.

所以==测试值,其中 is测试看看它们是否是同一个对象?

最佳答案

如果两个变量指向同一个对象(在内存中),

is 将返回 True,如果引用的对象是 ==变量是相等的。

>>> a = [1, 2, 3]
>>> b = a
>>> b is a
True
>>> b == a
True

# Make a new copy of list `a` via the slice operator,
# and assign it to variable `b`
>>> b = a[:]
>>> b is a
False
>>> b == a
True

就您而言,第二个测试仅有效,因为 Python 缓存了小整数对象,这是一个实现细节。对于更大的整数,这不起作用:

>>> 1000 is 10**3
False
>>> 1000 == 10**3
True

这同样适用于字符串文字:

>>> "a" is "a"
True
>>> "aa" is "a" * 2
True
>>> x = "a"
>>> "aa" is x * 2
False
>>> "aa" is intern(x*2)
True

请参阅this question也是如此。

关于python - "=="和 "is"之间有区别吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53352939/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com