将列表的一部分就地排序 [英] Sort a part of a list in place
本文介绍了将列表的一部分就地排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我们有一个列表:
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.
这篇关于将列表的一部分就地排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文