相关疑难解决方法(0)

"是"运算符与整数意外行为

为什么以下在Python中出现意外行为?

>>> a = 256
>>> b = 256
>>> a is b
True           # This is an expected result
>>> a = 257
>>> b = 257
>>> a is b
False          # What happened here? Why is this False?
>>> 257 is 257
True           # Yet the literal numbers compare properly
Run Code Online (Sandbox Code Playgroud)

我使用的是Python 2.5.2.尝试一些不同版本的Python,似乎Python 2.3.3显示了99到100之间的上述行为.

基于以上所述,我可以假设Python在内部实现,使得"小"整数以不同于大整数的方式存储,is运算符可以区分.为什么泄漏抽象?当我不知道它们是否是数字时,比较两个任意对象以查看它们是否相同的更好的方法是什么?

python int identity operators python-internals

476
推荐指数
11
解决办法
6万
查看次数

比较字符串和空格时,'is'运算符的行为不同

我开始学习Python(python 3.3),我正在尝试is运算符.我试过这个:

>>> b = 'is it the space?'
>>> a = 'is it the space?'
>>> a is b
False
>>> c = 'isitthespace'
>>> d = 'isitthespace'
>>> c is d
True
>>> e = 'isitthespace?'
>>> f = 'isitthespace?'
>>> e is f
False
Run Code Online (Sandbox Code Playgroud)

似乎空间和问号使is行为表现不同.这是怎么回事?

编辑:我知道我应该使用==,我只是想知道为什么is会这样.

python operators object-identity python-3.x

29
推荐指数
3
解决办法
1908
查看次数