python - 为什么容器的最大尺寸有符号位?

标签 python python-3.x containers size signed

我在 Python 3.6 中检查了 sys.maxsize 的帮助:

>>> help(sys)
[...]
maxsize -- the largest supported length of containers.

测试它:

In [10]: '{:,}'.format(sys.maxsize)
Out[10]: '9,223,372,036,854,775,807'

In [11]: math.log2(sys.maxsize)
Out[11]: 63.0

它是 63 位,表示前导符号位。但是,容器的长度不能为负数。

这是怎么回事?

最佳答案

容器的最大大小在 Python 2.5 中从 231-1 增加到 263-1。 PEP 353: Using ssize_t as the index type ,引入了变化,says :

Why not size_t

An initial attempt to implement this feature tried to use size_t. It quickly turned out that this cannot work: Python uses negative indices in many places (to indicate counting from the end). Even in places where size_t would be usable, too many reformulations of code where necessary, e.g. in loops like:

for(index = length-1; index >= 0; index--)

This loop will never terminate if index is changed from int to size_t.

因此,限制源于使用特定于 Python 的“索引”类型的决定,为了简化负索引的处理,将其定义为有符号 (ssize_t) 而不是无符号 (size_t) 很方便。

关于python - 为什么容器的最大尺寸有符号位?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54938095/

相关文章:

python - OpenCV KCF 跟踪预选对象

Python:枚举

python - 了解 maxmin 函数

docker - Docker:无法将数据从Logstash容器发送到Kafka容器

python - 使用 print 函数的 "*"参数打印由破折号分隔的 "sep"个字符

python-3.x - python中有没有可用的库来提取wav格式的音频功能,例如meanfreq,median,sd,Q25,dfrange,modindex,sp.ent,meanfun

python - 如何在 python 中编辑请求以添加 TLS 设置?

c++ - 使用C++在O(log n)中查找具有查找和插入/删除操作的索引容器

c - 如何使用 for() 表达式枚举循环链表?

python - 创建与矩形不同形状的 pyside 应用程序