📜  Python中的 sys.maxsize()

📅  最后修改于: 2022-05-13 01:55:11.663000             🧑  作者: Mango

Python中的 sys.maxsize()

sys模块的maxsize属性获取数据类型为Py_ssize_t的变量的最大值 可以存储。 Python平台的指针决定了Python中列表和字符串的最大大小。 maxsize 返回的大小值取决于平台架构:

  • 32 位:值将是 2^31 – 1,即2147483647
  • 64 位:该值将是 2^63 – 1,即9223372036854775807

sys.maxsize

示例 1:让我们在 64 位系统上获取最大的 Py_ssize_t 值。

Python3
# importing the module
import sys
       
# fetching the maximum value
max_val = sys.maxsize
print(max_val)


Python3
# importing the module
import sys
       
# fetching the maximum value
max_val = sys.maxsize
 
# creating list with max size
list = range(max_val)
 
# displaying the length of the list
print(len(list))
 
print("List successfully created")


Python3
# importing the module
import sys
       
# fetching the maximum value
max_val = sys.maxsize
 
try:
 
    # creating list with max size + 1
    list = range(max_val + 1)
 
    # displaying the length of the list
    print(len(list))
    print("List successfully created")
     
except Exception as e:
 
    # displaying the exception
    print(e)
    print("List creation unsuccessful")


输出:

9223372036854775807

示例 2:创建具有最大大小的列表。

蟒蛇3

# importing the module
import sys
       
# fetching the maximum value
max_val = sys.maxsize
 
# creating list with max size
list = range(max_val)
 
# displaying the length of the list
print(len(list))
 
print("List successfully created")
输出
9223372036854775807
List successfully created

输出:

9223372036854775807
List successfully created

示例 3:尝试创建一个大小大于最大大小的列表。

蟒蛇3

# importing the module
import sys
       
# fetching the maximum value
max_val = sys.maxsize
 
try:
 
    # creating list with max size + 1
    list = range(max_val + 1)
 
    # displaying the length of the list
    print(len(list))
    print("List successfully created")
     
except Exception as e:
 
    # displaying the exception
    print(e)
    print("List creation unsuccessful")
输出
Python int too large to convert to C ssize_t
List creation unsuccessful

输出:

Python int too large to convert to C ssize_t
List creation unsuccessful