在适当位置对列表的一部分进行排序

编程入门 行业动态 更新时间:2024-10-23 22:28:29
本文介绍了在适当位置对列表的一部分进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

假设我们有一个列表:

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.

更多推荐

在适当位置对列表的一部分进行排序

本文发布于:2023-06-07 22:02:46,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/568568.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:位置   列表

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!