就地排序子列表

wim*_*wim 8 python sorting list view slice

可能吗?显然x[1:-1].sort()不起作用,因为切片是副本.

目前的解决方法:

>>> x = [4, 3, 1, 2, 5]
>>> s = slice(1, -1)
>>> x[s] = sorted(x[s])
>>> x
[4, 1, 2, 3, 5]
Run Code Online (Sandbox Code Playgroud)

我可以以某种方式获取python列表上的视图吗?

Nig*_*nel 5

如果numpy是一个选项:

>>> x = np.array([1, 8, 90, 30, 5])
>>> x[2:].sort()
>>> x
array([ 1,  8,  5, 30, 90])
Run Code Online (Sandbox Code Playgroud)

numpy数组切片始终是原始数组的视图.