首页 > 解决方案 > why i cannot use chain expression in numpy?

问题描述

This don't work:

import numpy as np
np.random.random(10).sort() 

this is ok:

Z = np.random.random(10)
Z.sort()

Please tell me why the chain expression don't work in Numpy.

标签: pythonnumpy

解决方案


Just like list.sort, numpy.ndarray.sort sorts in-place, meaning that it mutates the array and then returns None.

help(numpy.ndarray.sort) ->

sort(...)
a.sort(axis=-1, kind='quicksort', order=None)
Sort an array, in-place.

With

np.random.random(10).sort() 

you won't see any output in the REPL because None is not displayed. (Even if this line produced a value other than None, which it does not, it would be pretty pointless since you don't assign any name.)

In the second example, you create an array Z and then sort it, which works as expected.


推荐阅读