我在 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/