python中的IS运算符 [英] IS operator in python

查看:109
本文介绍了python中的IS运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

代码第1部分:



code part1:

name1="rahul"
name2="rahul"







code part2:






code part2:

name1=[1,2,3]
name2=[1,2,3]





如果我运行以下代码:





If I run the following code:

print name1 is name2





我得到True代码第1部分



我得到False代码第2部分



为什么?为什么引用对于代码部分1中的name1和name2是相同的,而对于代码部分2中的name1和name2则不同



I get "True" for code part1
and
I get "False" for code part2

why? why the "reference" is same for name1 and name2 in "code part 1" and different for name1 and name2 in "code part 2"

推荐答案

这必须做以及Python如何在内部存储字符串。具有相同内容的两个字符串文字存储为相同的字符串实例 1 。由于字符串是不可变的,因此可以这样做。第一个示例使用字符串,因此从相同的字符串文字创建的字符串都指向同一个字符串实例。第二个例子是数组。由于数组是可变的,因此为每个数组文字创建了一个新实例,这就是为什么 Is 运算符在后一种情况下将返回false而在前一种情况下为true的原因。 />


问候,



- 曼弗雷德
1 这对于构造为具有相同内容的字符串,情况并非如此。在此处查看此SO条目: Python'=='vs'是比较字符串,有时会失败,为什么?[ ^ ]
This has to do with how Python stores strings internally. Two string literals that have the same content are stored as the same string instance1. Since strings are immutable this is OK to do so. The first sample uses strings so both the strings created from the same string literals are both pointing to the same string instance. The second example is with arrays. Since arrays are mutable a new instance is created for each array literal and that is the reason why the Is operator will return false in the latter case while true in the former.

Regards,

— Manfred
1This is not true for strings that are constructed to have the same content. See this SO entry here: Python '==' vs 'is' comparing strings, 'is' fails sometimes, why?[^]


这篇关于python中的IS运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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