문제

I'm observing some odd behavior. Here is the snippet of code:

>>> import numpy as np
>>> a = [[1, .3], [0, .5], [2, .23]]
>>> b = np.array(a.sort())
>>> b
array(None, dtype=object)

Is this behavior expected? If I add an intermediate step for the in-place sort, it works as expected:

>>> a = [[1, .3], [0, .5], [2, .23]]
>>> a.sort()
>>> b = np.array(a)
>>> b
array([[ 0.  ,  0.5 ],
       [ 1.  ,  0.3 ],
       [ 2.  ,  0.23]])

Can someone explain what is happening?

도움이 되었습니까?

해결책

The issue is that a.sort() does not return the sorted list. It returns None:

>>> a.sort() is None
True

You could use sorted(a):

>>> b = np.array(sorted(a))
>>> b
array([[ 0.  ,  0.5 ],
       [ 1.  ,  0.3 ],
       [ 2.  ,  0.23]])

However, this would create a (sorted) copy of a.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top