迹忆客 专注技术分享

当前位置:主页 > 学无止境 > 编程语言 > Python >

Python 错误 OverflowError: Python Int Too Large to Convert to C Long

作者:迹忆客 最近更新:2023/05/30 浏览次数:

本篇文章将介绍 Python 中的 OverflowError: python int too large to convert to c long 错误。


Python 错误OverflowError: python int too large to convert to c long

当算术结果超出数据类型的给定限制时,Python 中会引发 OverflowError。 我们遇到此指定错误是因为我们尝试使用大于给定范围的整数值进行操作。

代码:

import numpy as np
arr = np.zeros((1, 2), dtype=int)
a = [6580225610007]
arr[0] = a

输出:

OverflowError: Python int too large to convert to C long

上面的例子创建了一个 int 类型的数组。 我们尝试存储一个包含大于 int 类型范围的整数的列表。

还可以使用 sys 库中的常量检查最大大小。 该常量作为 sys.maxsize 可用。


修复Python中 OverflowError: Python int too large to convert to C long 错误

为了避免这个错误,我们必须注意我们可以使用 int 类型的最大范围。 存在一个修复程序,尤其是在这个关于 numpy 数组的示例中。

int 类型等同于 C 语言的 long int 类型,在 Python 3 中被改变,int 类型被转换为任意精度类型。

但是,numpy 库仍然按照 Python 2 中声明的方式使用它。long int 通常是平台相关的,但对于 windows,它始终是 32 位的。

要修复此错误,我们可以使用不依赖于平台的其他类型。 最常见的替代方案是 np.int64 类型,我们在数组中使用 dtype 参数指定它。

代码:

import numpy as np
arr = np.zeros((1, 2), dtype=np.int64)
a = [6580225610007]
arr[0] = a
print(arr)

输出:

[[6580225610007 6580225610007]]

上面的示例显示错误已使用替代类型解决。

另一种方法是使用 try 和 except 块。 这两个块用于解决 Python 中的异常。

如果 try 块中抛出异常,则执行 except 块中的代码。

代码:

import numpy as np
arr = np.zeros((1, 2), dtype=int)
a = [6580225610007]
try:
    arr[0] = a
except:
    print("Error in code")

输出:

Error in code

上面的示例使用 try 和 except 块避免了错误。

请记住 ,这不是对给定错误的修复,而是一种解决错误的方法。

转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处

本文地址:

相关文章

Pandas read_csv()函数

发布时间:2024/04/24 浏览次数:254 分类:Python

Pandas read_csv()函数将指定的逗号分隔值(csv)文件读取到 DataFrame 中。

Pandas 追加数据到 CSV 中

发布时间:2024/04/24 浏览次数:352 分类:Python

本教程演示了如何在追加模式下使用 to_csv()向现有的 CSV 文件添加数据。

Pandas 多列合并

发布时间:2024/04/24 浏览次数:628 分类:Python

本教程介绍了如何在 Pandas 中使用 DataFrame.merge()方法合并两个 DataFrames。

Pandas loc vs iloc

发布时间:2024/04/24 浏览次数:837 分类:Python

本教程介绍了如何使用 Python 中的 loc 和 iloc 从 Pandas DataFrame 中过滤数据。

扫一扫阅读全部技术教程

社交账号
  • https://www.github.com/onmpw
  • qq:1244347461

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便