Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In-place sort of sublist

Is it possible? Obviously x[1:-1].sort() doesn't work because the slice is a copy.

Current workaround:

>>> x = [4, 3, 1, 2, 5]
>>> s = slice(1, -1)
>>> x[s] = sorted(x[s])
>>> x
[4, 1, 2, 3, 5]

Can I somehow get a view on a python list?

like image 552
wim Avatar asked Jan 27 '14 12:01

wim


1 Answers

If numpy is an option:

>>> x = np.array([1, 8, 90, 30, 5])
>>> x[2:].sort()
>>> x
array([ 1,  8,  5, 30, 90])

numpy array slices are always views of the original array.

like image 172
Nigel Tufnel Avatar answered Oct 31 '22 18:10

Nigel Tufnel