“ ==”与“和“是”? [英] Is there a difference between "==" and "is"?

查看:118
本文介绍了“ ==”与“和“是”?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的 Google-fu 使我失败了。

在Python中,以下两个相等性测试是否相等?

In Python, are the following two tests for equality equivalent?

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

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

是否保留对于要在其中比较实例的对象(例如列表说)是否正确?

Does this hold true for objects where you would be comparing instances (a list say)?

好吧,所以这种答案我的问题:

Okay, so this kind of answers my question:

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

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

所以 == 测试值,其中进行测试以查看它们是否是同一对象?

So == tests value where is tests to see if they are the same object?

推荐答案

<$ c如果两个变量指向同一个对象,则$ c> is 将返回 True ==

is will return True if two variables point to the same object, == if the objects referred to by the variables are equal.

>>> 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缓存小整数对象,这是一个实现细节。对于较大的整数,这将不起作用:

In your case, the second test only works because Python caches small integer objects, which is an implementation detail. For larger integers, this does not work:

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

对于字符串文字也是如此: / p>

The same holds true for string literals:

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

请参见这个问题

这篇关于“ ==”与“和“是”?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆