Sort a part of a list in place

后端 未结 3 479
野性不改
野性不改 2020-11-29 03:39

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

3条回答
  •  -上瘾入骨i
    2020-11-29 03:43

    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.

提交回复
热议问题