脾气暴躁:我应该使用newaxis还是None? [英] Numpy: Should I use newaxis or None?
问题描述
在numpy中,可以使用切片语法中的'newaxis'对象创建长度为1的轴,例如:
In numpy one can use the 'newaxis' object in the slicing syntax to create an axis of length one, e.g.:
import numpy as np
print np.zeros((3,5))[:,np.newaxis,:].shape
# shape will be (3,1,5)
文档状态也使用None
代替newaxis
,效果是完全一样的.
The documentation states that one can also use None
instead of newaxis
, the effect is exactly the same.
是否有任何理由选择一个?是否有一般偏好或样式指南?我的印象是newaxis
更为流行,可能是因为它更明确.那么,为什么有任何理由允许None
?
Is there any reason to choose one over the other? Is there any general preference or style guide? My impression is that newaxis
is more popular, probably because it is more explicit. So is there any reason why None
is allowed?
推荐答案
None
,因为numpy.newaxis
仅仅是None
的别名.
None
is allowed because numpy.newaxis
is merely an alias for None
.
In [1]: import numpy
In [2]: numpy.newaxis is None
Out[2]: True
作者之所以选择它是因为他们需要一个方便的常量,并且可以使用None
.
The authors probably chose it because they needed a convenient constant, and None
was available.
关于为什么比None
更喜欢newaxis
的原因:主要是因为它更明确,部分原因是有一天numpy
的作者可能会将其更改为None
以外的其他名称. (他们并不打算也可能不会,但是没有充分的理由偏爱None
.)
As for why you should prefer newaxis
over None
: mainly it's because it's more explicit, and partly because someday the numpy
authors might change it to something other than None
. (They're not planning to, and probably won't, but there's no good reason to prefer None
.)
这篇关于脾气暴躁:我应该使用newaxis还是None?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!