Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/286.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/python-2.7/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 2.7是否存储重复字符串_Python_Python 2.7 - Fatal编程技术网

Python 2.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

想知道我的两个例子,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[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