卓越飞翔博客卓越飞翔博客

卓越飞翔 - 您值得收藏的技术分享站
技术文章19476本站已运行343

在Python中,"!="和"is not"运算符之间的区别是什么?

在Python中,"!="和"is not"运算符之间的区别是什么?

!= 操作符用于检查被比较的两个对象的值是否相等。另一方面,“is not” 操作符用于检查被比较的两个对象是否指向不同的引用。如果被比较的对象不指向相同的引用,则 “is not” 操作符返回 true,否则返回 false。在本文中,我们将讨论如何使用 !=“is not” 操作符,以及它们之间的区别。

!= 操作符

“不是”运算符

!= 运算符仅比较所比较对象的值。

“is not”运算符用于比较对象是否指向相同的内存位置。

如果两个对象的值不同,则返回 True,否则返回 False

如果对象没有指向同一内存位置,则返回 true,否则返回 false。

!= 运算符的语法是 object1 != object2

“is not”运算符的语法是 object1 is not object2

Example

的中文翻译为:

示例

在下面的示例中,我们借助!=运算符和“不是”运算符比较具有不同数据类型(例如整数、字符串和列表)的两个对象值,以查看两者之间的差异都是运营商。

'
# python code to differentiate between != and “is not” operator.

# comparing object with integer datatype
a = 10
b = 10
print("comparison with != operator",a != b)
print("comparison with is not operator ", a is not b)
print(id(a), id(b))

# comparing objects with string data type
c = "Python"
d = "Python"
print("comparison with != operator",c != d)
print("comparison with is not operator", c is not d)
print(id(c), id(d))

# comparing list
e = [ 1, 2, 3, 4]
f=[ 1, 2, 3, 4]
print("comparison with != operator",e != f)
print("comparison with is not operator", e is not f)
print(id(e), id(f))

输出

'
comparison with != operator False
comparison with is not operator  False
139927053992464 139927053992464
comparison with != operator False
comparison with is not operator False
139927052823408 139927052823408
comparison with != operator False
comparison with is not operator True
139927054711552 139927052867136

结论

在本文中,我们讨论了 != 运算符和“is not”运算符之间的差异,以及如何使用这两个比较运算符来比较两个对象。 != 运算符仅比较值,而“is not”运算符检查所比较对象的内存位置。在比较两个对象时,这两个运算符都可以在不同的场景中使用。

卓越飞翔博客
上一篇: PHP开发互关注系统的性能优化与调优指南
下一篇: 返回列表
留言与评论(共有 0 条评论)
   
验证码:
隐藏边栏