我正在使用带有numpy的矩阵进行相当复杂的求和.矩阵matrix.shape = (500, 500)的形状是和阵列的形状arr.shape = (25,).操作如下:
totalsum = np.sum([i * matrix for i in arr])
Run Code Online (Sandbox Code Playgroud)
这是我不明白的:
np.sum()很慢并返回一个浮点数float64.用Python做同样的操作sum.(),即
totalsum2 = sum([i*matrix for i in arr])
Run Code Online (Sandbox Code Playgroud)
保留矩阵的形状.也就是说,产生的形状是totalsum2.shape() = (500, 500).咦?
我也觉得奇怪的是np.sum()需要更长的时间sum(),特别是当我们使用numpy ndarrays时.
到底发生了什么?如何np.sum()比较上述值sum()?
我想np.sum()保留矩阵形状.如何设置尺寸以np.sum()保留矩阵尺寸并且不返回单个浮动?
我最近重新安装nose了对我的代码运行测试.
https://nose.readthedocs.org/en/latest/
我用了
sudo pip install nose
Run Code Online (Sandbox Code Playgroud)
并转到我的项目文件夹.回应是
-bash: nosetests: command not found.
Run Code Online (Sandbox Code Playgroud)
所以,我再次卸载并尝试nose使用MacPorts进行安装:
sudo port install py27-nose
Run Code Online (Sandbox Code Playgroud)
在我的项目文件夹中,我运行
nosetests-2.7 filename.py
Run Code Online (Sandbox Code Playgroud)
我收到以下错误:
ERROR: Failure: ImportError (No module named nose_parameterized)
Run Code Online (Sandbox Code Playgroud)
有什么问题?
编辑:更多信息.nose已安装.我得到Successfully installed nose-1.3.6.
这在Python教程中有介绍,但我还是不太明白Python为什么会有这种风格。是纯粹的约定,还是有一些解释为什么 Python 对默认参数具有以下样式:
我的理解是 Python 更喜欢something=None而不是something=[]函数的默认参数。但是……为什么不使用something=[]?当然这是其他语言的约定,比如 C
以这两个例子为例,它们是等价的
def function(arr, L=[]):
L.append(arr)
return L
Run Code Online (Sandbox Code Playgroud)
和
def function(arr, L=None):
if L is None:
L = []
L.append(arr)
return L
Run Code Online (Sandbox Code Playgroud)
我的理解是,第一个是 Python 的“风格不正确”。为什么?
编辑:啊,我终于明白了。我上面不正确:这两个函数不等价。默认参数在定义函数时计算一次,而不是每次调用函数时!