Python 2.7是否存储重复字符串
想知道我的两个例子,Python2.7是存储重复的字符串文字Python 2.7是否存储重复字符串,python,python-2.7,Python,Python 2.7,想知道我的两个例子,Python2.7是存储重复的字符串文字Hello,还是存储一个字符串文字Hello,并且只存储字符串文字的地址以节省空间?谢谢 我的两个案例显示了如何使用string literal和string(str)变量 from collections import defaultdict a = defaultdict(list) # case 1 a[1].append("Hello") a[2].append("Hello") # case 2 b = "Hello" a
Hello
,还是存储一个字符串文字Hello
,并且只存储字符串文字的地址以节省空间?谢谢
我的两个案例显示了如何使用string literal和string(str
)变量
from collections import defaultdict
a = defaultdict(list)
# case 1
a[1].append("Hello")
a[2].append("Hello")
# case 2
b = "Hello"
a[3].append(b)
a[4].append(b)
在案例2中,您可以安全地假设同一对象被引用了两次,因为这是您显式执行的操作。请记住,在Python中,您总是会对引用进行折腾。同时,第一个案例有点复杂。CPython通过缓存短字符串(以及小数字)来优化内存使用,例如 换句话说,
a是b
返回True
。但这不是您可以依赖的,因为不同版本和构建之间的大小阈值可能不同
In [8]: c = "Quite a long string this is. It's supposed to demonstrate CPython's tweaks"
In [9]: d = "Quite a long string this is. It's supposed to demonstrate CPython's tweaks"
In [10]: c is d
Out[10]: False
根据我的实验,
c is d
一旦遇到非单词字符就不再是真的了。@daragua我没有注意到这一点。根据我的经验,只有一个长度阈值。例如,对于c=“qwertyuiopasdfghjklzxcvbnqwertyuiopasdfgklzxcvbnqwertyuiopasdfghjklzxcvbnm”
和d=“qwertyuiopasdfgkvbnqwertyuiopasdfghjklzvcnmqwertyuiopasdfghjklzvbnqwertyuiopasdfgjcklzvjklzjklzvcnm”
返回False,虽然只存在字母字符。c=“azerty”
和d=“azerty”
,c为d
时,似乎至少存在两种情况。顺便说一句,“azerty”是“azerty”
是真的
,就像你的长字符串一样。@daragua我已经有一段时间没有访问这个线程了<代码>“azerty”是“azerty”是真的
,因为另一个优化开始了:CPython可以在同一个表达式中重用文本。
In [8]: c = "Quite a long string this is. It's supposed to demonstrate CPython's tweaks"
In [9]: d = "Quite a long string this is. It's supposed to demonstrate CPython's tweaks"
In [10]: c is d
Out[10]: False