Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/352.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 显示返回的行';空切片的平均值';_Python_List_Numpy_Error Handling_Printing - Fatal编程技术网

Python 显示返回的行';空切片的平均值';

Python 显示返回的行';空切片的平均值';,python,list,numpy,error-handling,printing,Python,List,Numpy,Error Handling,Printing,我的代码中有多个实例,其中我计算列表的平均值。因此,我正在寻找一种方法来显示出现警告“meansofempty slice”的代码行,就像任何正常错误一样 输入为普通列表[1,2,3]或numpy列表 np.array([1,2,3]) 所以我想要这样的东西: 文件“File_name.py”,行中 到目前为止,我可以打印所有平均值计算的输出,如下所示: test1 = np.mean([1,2,3]) print('test1',test1) 但是,我认为,对于代码中有许多这样的计算的情况来

我的代码中有多个实例,其中我计算列表的平均值。因此,我正在寻找一种方法来显示出现警告“meansofempty slice”的代码行,就像任何正常错误一样

输入为普通列表
[1,2,3]
或numpy列表
np.array([1,2,3])

所以我想要这样的东西:
文件“File_name.py”,行中

到目前为止,我可以打印所有平均值计算的输出,如下所示:

test1 = np.mean([1,2,3])
print('test1',test1)
但是,我认为,对于代码中有许多这样的计算的情况来说,这太多余了


是否有办法更改警告的配置,使其返回此信息?

您可以使用
np.seterr(all='raise')
将所有numpy警告升级为错误

这样,当存在一个空切片的平均值时,您的代码将抛出一个异常并中断,您将能够看到它发生的位置:

>>> import numpy as np
>>> np.seterr(all="raise")
{'divide': 'warn', 'over': 'warn', 'under': 'ignore', 'invalid': 'warn'}
>>> np.mean([]) # raises FloatingPointError

对于任何numpython和普通python列表,您得到这个错误的原因是什么