gpt4 book ai didi

python - python 如何存储字符串以便 'is' 运算符对文字起作用?

转载 作者:太空狗 更新时间:2023-10-30 01:20:24 25 4
gpt4 key购买 nike

在 python 中

>>> a = 5
>>> a is 5
True

但是

>>> a = 500
>>> a is 500
False

这是因为它将低整数存储为单个地址。但是一旦数字开始变得复杂,每个 int 都有自己独特的地址空间。这对我来说很有意义。

The current implementation keeps an array of integer objects for all integers between -5 and 256, when you create an int in that range you actually just get back a reference to the existing object.

那么现在,为什么这不适用于字符串?字符串不是和大整数一样复杂(如果不是更复杂的话)吗?

>>> a = '1234567'
>>> a is '1234567'
True

python 如何有效地为所有字符串文字使用相同的地址?它不能像处理数字那样保留每个可能字符串的数组。

最佳答案

这是一种称为实习的优化技术。 CPython 识别 equal values of string constants并且不为新实例分配额外的内存,而是简单地指向同一个实例(实习生它),给两个相同的 id()

可以尝试确认只有常量以这种方式处理(可以识别像 b 这样的简单操作):

# Two string constants
a = "aaaa"
b = "aa" + "aa"

# Prevent interpreter from figuring out string constant
c = "aaa"
c += "a"

print id(a) # 4509752320
print id(b) # 4509752320
print id(c) # 4509752176 !!

但是,您可以使用 intern() 手动强制将字符串映射到已存在的字符串。 :

c = intern(c)

print id(a) # 4509752320
print id(b) # 4509752320
print id(c) # 4509752320 !!

其他口译员的做法可能有所不同。由于字符串是不可变的,因此改变两者之一不会改变另一个。

关于python - python 如何存储字符串以便 'is' 运算符对文字起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40009015/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com