一农 发表于 2024-5-9 19:04:49

python中小数据池和编码

⼀. 小数据池

在说小数据池之前. 我们先看⼀个概念. 什么是代码块:
根据提示我们从官⽅⽂档找到了这样的说法:
A Python program is constructed from code blocks. A block is a piece of Python program text that is executed as a unit. The following are blocks: a module, a function body, and a class definition. Each command typed interactively is a block. A script file (a file given as standard input to the interpreter or specified as a command line argument to the interpreter) is a code block. A script command (a command specified on the interpreter command line with the ‘-c‘ option) is a code block. The string argument passed to the built-in functions eval() and exec() is a code block. A code block is executed in an execution frame. A frame contains some administrative information (used for debugging) and determines where and how execution continues after the code block’s execution has completed.
粗略的翻译:
python程序是由代码块构成的. ⼀个代码块的⽂本作为python程序执⾏的单元. 代码块: ⼀个模块, ⼀个函数, ⼀个类,
甚⾄每⼀个command命令都是⼀个代码块. ⼀个⽂件也是⼀ 个代码块, eval()和exec()执⾏的时候也是⼀个代码块
二、接下来我们来看一下小数据池is和 ==的区别

1、id( )
通过id( )我们可以查看到一个变量表示的值的内存地址
s = 'alex'
print(id(s)) # 43266670722、is和==
== 判断左右两段的值是否相等,是否一致
is 判断左右两端的内存地址是否一致,如果一致就返回True
注意:如果内存地址相同. 那么值⼀定是相等的;如果值相等. 则不⼀定是同⼀个对象 。
3、小数据池.:⼀种数据缓存机制. 也被称为驻留机制.
小数据池只针对: 整数, 字符串, 布尔值. 其他的数据类型不存在驻留机制 。
对于整数, Python官⽅⽂档中这么说:
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. So it should be possible to change the value of 1. I suspect the behaviour of Python in this case is undefined.
对于字符串:
Incomputer science, string interning is a method of storing only onecopy of each distinct string value, which must be immutable. Interning strings makes some stringprocessing tasks more time- or space-efficient at the cost of requiring moretime when the string is created or interned. The distinct values are stored ina string intern pool. –引⾃维基百科
在python中对-5到256之间的整数会被驻留在内存中,将一定规则的字符串缓存,在使用的时候,内存中只会创建一个该数据的对象,保存小数据池中,当使用的时候直接从
小数据池中获取对象的内存引用,二不需要创建一个新的数据,这样可以节省更多的内存。

[*]优点:能够提高一些字符串、整数的处理速度,省去了创建对象的过程。
[*]缺点:在”池“中插入或者创建新值会花费更多时间。
对于数字: -5~256是会被加到⼩数据池中的. 每次使⽤都是同⼀个对象.
对于字符串:
<ol>如果字符串的⻓度是0或者1, 都会默认进⾏缓存
字符串⻓度⼤于1, 但是字符串中只包含字⺟, 数字, 下划线时才会缓存
⽤乘法的到的字符串.
①. 乘数为1, 仅包含数字, 字⺟, 下划线时会被缓存. 如果包含其他字符, ⽽⻓度 encode(字符集)来完成</p>a = 1000
b = 1000
print(a is b)s = "alex"
print(s.encode("utf-8")) # 将字符串编码成UTF-8
print(s.encode("GBK")) # 将字符串编码成GBK

#结果:
b'alex'b'alex'解码
s = "中"
print(s.encode("UTF-8")) # 中⽂编码成UTF-8
print(s.encode("GBK")) # 中⽂编码成GBK

#结果:
b'\xe4\xb8\xad'
b'\xd6\xd0编码和解码的时候都需要制定编码格式.
s = "我叫李嘉诚"
print(s.encode("utf-8")) #
b'\xe6\x88\x91\xe5\x8f\xab\xe6\x9d\x8e\xe5\x98\x89\xe8\xaf\x9a'
print(b'\xe6\x88\x91\xe5\x8f\xab\xe6\x9d\x8e\xe5\x98\x89\xe8\xaf\x9a'.decode("utf-8")) # 解码
来源:https://www.cnblogs.com/xxpythonxx/p/18182546
免责声明:由于采集信息均来自互联网,如果侵犯了您的权益,请联系我们【E-Mail:cb@itdo.tech】 我们会及时删除侵权内容,谢谢合作!
页: [1]
查看完整版本: python中小数据池和编码