Sort a part of a list in place

≯℡__Kan透↙ 提交于 2019-12-17 09:18:06

问题


Let's say we have a list:

a = [4, 8, 1, 7, 3, 0, 5, 2, 6, 9]

Now, a.sort() will sort the list in place. What if we want to sort only a part of the list, still in place? In C++ we could write:

int array = { 4, 8, 1, 7, 3, 0, 5, 2, 6, 9 };
int * ptr = array;
std::sort( ptr + 1, ptr + 4 );

Is there a similar way in Python?


回答1:


I'd write it this way:

a[i:j] = sorted(a[i:j])

It is not in-place sort either, but fast enough for relatively small segments.

Please note, that Python copies only object references, so the speed penalty won't be that huge compared to a real in-place sort as one would expect.




回答2:


if a is a numpy array then to sort [i, j) range in-place, type:

a[i:j].sort()

Example:

>>> import numpy as np
>>> a = np.array([4, 8, 1, 7, 3, 0, 5, 2, 6, 9])
>>> a[1:4].sort()
>>> a
array([4, 1, 7, 8, 3, 0, 5, 2, 6, 9])



回答3:


Based on your requirements, I'd suggest creating your own sort function/ a wrapper class for the list with a sort function which staisfies your requirement.

You might consider the DSU idiom or the schwartzian transform: See http://wiki.python.org/moin/HowTo/Sorting and http://wiki.python.org/moin/PythonSpeed/PerformanceTips. I suggest you decorate with 0 up until i, the element between i and j and 0 again j onwards. Then, use a custom comparison function to return 0 if either x or y is zero get the sort to work! This may not help, since we crossed Python V2.4 long ago. Still, this might be what you are looking for.

This answer fills in while I try figure out if it can be done with less effort!



来源:https://stackoverflow.com/questions/2272819/sort-a-part-of-a-list-in-place

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!