我应该使用 newaxis 还是 Nothing?

在 numpy 中,人们可以使用切片语法中的‘ newwaxis’对象来创建一个长度为1的轴,例如:

import numpy as np
print np.zeros((3,5))[:,np.newaxis,:].shape
# shape will be (3,1,5)

文件说明中也可以用 None代替 newaxis,效果完全一样。

有什么理由选择其中一个吗?是否有一般的偏好或风格指南?我的印象是 newaxis更受欢迎,可能是因为它更加明确。那么 None被允许的原因是什么呢?

28608 次浏览

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

The authors probably chose it because they needed a convenient constant, and None was available.

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.)