本文介绍了在适当位置对列表的一部分进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我们有一个列表:
a = [4, 8, 1, 7, 3, 0, 5, 2, 6, 9]现在,a.sort()将对列表进行排序.如果我们只想对列表的一部分进行排序,该怎么办呢?在C ++中,我们可以编写:
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 );Python中有类似的方法吗?
Is there a similar way in Python?
推荐答案我会这样写:
a[i:j] = sorted(a[i:j])它也不是就地排序,但是足够快以用于相对较小的段.
It is not in-place sort either, but fast enough for relatively small segments.
请注意,Python仅复制对象引用,因此与真正的就地排序相比,速度损失不会那么大.
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.
更多推荐
在适当位置对列表的一部分进行排序
发布评论