如何忽略复数的 Python 警告

How to ignore Python warnings for complex numbers

我有一个列表,需要包含实数值和复数值。但是,当我不使用 numpy.zeros(dtype=complex) 初始化数组时,出现以下错误:

n[2] = 3.7095 + 0.007j

TypeError: can't convert complex to float

但是,当我将 dtype 设置为复杂时,当我使用实数时会收到以下警告(这不会破坏我的代码,但会导致大量不必要的红色警告消息使我的控制台混乱:

ComplexWarning: Casting complex values to real discards the imaginary part

如何禁用警告消息,或以其他方式设置它以便值可以是虚数或复数?

您可以使用它来忽略警告消息:

import warnings
warnings.filterwarnings('ignore')

文档:https://docs.python.org/2/library/warnings.html

我已经包括了文档的 link 因为还有更多 "soft" 方法来处理警告,例如只打印第一次出现的警告 ('once') . 在您的情况下,也可以仅过滤某些 类 警告 (ComplexWarning)。