网页资讯视频图片知道文库贴吧地图采购
进入贴吧全吧搜索

 
 
 
日一二三四五六
       
       
       
       
       
       

签到排名:今日本吧第个签到,

本吧因你更精彩,明天继续来努力!

本吧签到人数:0

一键签到
成为超级会员,使用一键签到
一键签到
本月漏签0次!
0
成为超级会员,赠送8张补签卡
如何使用?
点击日历上漏签日期,即可进行补签。
连续签到:天  累计签到:天
0
超级会员单次开通12个月以上,赠送连续签到卡3张
使用连续签到卡
01月15日漏签0天
python吧 关注:480,825贴子:1,983,326
  • 看贴

  • 图片

  • 吧主推荐

  • 视频

  • 游戏

  • 25回复贴,共1页
<<返回python吧
>0< 加载中...

今天遇到一个诡异的问题: a="1-1"; a is not "1-1";结果是True

  • 只看楼主
  • 收藏

  • 回复
  • 53269743
  • 进士
    8
该楼层疑似违规已被系统折叠 隐藏此楼查看此楼
通过对id(a)和id("1-1")的比较发现id值确实不一样,但是python为什么会对带"-"的字符串做这样的处理呢????


  • nadesico19
  • 榜眼
    12
该楼层疑似违规已被系统折叠 隐藏此楼查看此楼
Interning Strings for Efficiency
The Python interpreter works a lot with strings, and like small integers, strings can also be reused by Python through a slightly different technique called interning. When a new string is created, the Python interpreter can choose whether or not to store a cached copy of that string. This happens under certain circumstances, in particular for identifiers.
Therefore, if a string starts with a letter or an underscore and only contains letters, underscores, or numbers, Python will intern the string and create a hash for it. As most things in Python are dictionaries, Python has to do a lot of lookups for identifiers, and by interning identifier strings the lookup process can be sped up quite a bit. In other words, identifiers are stored in a table, and Python creates a hash from the string object for future lookups. Such optimization occurs during compile time, and string literals that look like identifiers will also be interned.


2026-01-15 16:26:24
广告
不感兴趣
开通SVIP免广告
  • nadesico19
  • 榜眼
    12
该楼层疑似违规已被系统折叠 隐藏此楼查看此楼
如上文所说,python在编译期将满足标识符要求的字符串缓存是为了提高查表速度,相当于转换为了symbol。带"-"的字符串已经不满足标识符要求,所以就没这待遇咯。


  • 时尚花秋裤
  • 探花
    10
该楼层疑似违规已被系统折叠 隐藏此楼查看此楼
嘻嘻,此贴已被2楼终结.
原理就是那个样子的.
===========================================================
以下都是我之前的猜测加鬼故事.
python的str等类型的内部存储形式可能采用了蝇量模式来复用.
>>> a is b 等价于 id(a) == id(b)
例1:a ,b 一回事
>>>a=4
>>>b=4
>>>id(a) == id(b) #True
例2:从a is c看得出python内部是有一些小动作(优化)的.
>>>c=2**2
>>>id(a) == id(c) #True
例3: 再给我复用一个看看呀?
>>>[] is [] #False
>>>{} is {} #False
例4:什么原理?什么可变不可变论呼之欲出.
>>>None is None #True
>>>() is () #True
例5:将计就计解锁下一个鬼故事
>>>123 is 1.23*100 #False
>>>123 == 1.23*100 #True


  • 53269743
  • 进士
    8
该楼层疑似违规已被系统折叠 隐藏此楼查看此楼
谢谢给位大哥的解答.


  • 电离的Tesla
  • 探花
    10
该楼层疑似违规已被系统折叠 隐藏此楼查看此楼
似乎不可变是必要条件,而不是充分条件
() is () // True
(256) is (256) // True
(257) is (257) // False


  • nadesico19
  • 榜眼
    12
该楼层疑似违规已被系统折叠 隐藏此楼查看此楼
从下面的现象上看:
1. 在同一个语句内出现相等的不变对象时会指向同一个对象,而不同语句内出现的不变对象就不一定了。
2. 看来python对int对象的缓存范围只到256为止。
>>> 257 is 257
True
>>> a, b = 257, 257
>>> a is b
True
>>> a = 257
>>> b = 257
>>> a is b
False
>>> a = 256
>>> b = 256
>>> a is b
True


登录百度账号

扫二维码下载贴吧客户端

下载贴吧APP
看高清直播、视频!
  • 贴吧页面意见反馈
  • 违规贴吧举报反馈通道
  • 贴吧违规信息处理公示
  • 25回复贴,共1页
<<返回python吧
分享到:
©2026 Baidu贴吧协议|隐私政策|吧主制度|意见反馈|网络谣言警示