如何使用另一个列表中的索引对列表进行切片

How to slice a list using indexes in another list

我从一个长列表开始,比如说 4438。我需要创建一个包含该起始列表的子列表的列表。为此,我有一个索引列表:

indexes = [0, 888, 1776, 2664, 3551, 4438]

这意味着,在我的最终列表中,第一个子列表采用前 888 个元素,第二个子列表采用以下 888 个元素,第三个采用以下 888 个元素,依此类推。

我需要的子列表是:

sublist_1 = list_to_slice[0:888]
sublist_2 = list_to_slice[888:1776]
sublist_3 = list_to_slice[1776:2664]
...

我的代码:

final_list = [list_to_slice[i:i+1] for i in indexes]

我的代码的问题在于,它没有进行上述切片,而是:

sublist_1 = list_to_slice[0:1]
sublist_2 = list_to_slice[888:889]
sublist_3 = list_to_slice[1776:1777]
...

i+1 被视为 'add 1 to the index i' 而不是 'take the index that follows i',我怎样才能获得执行后者的代码?我需要一段很好的代码来进行这种切片,我不在乎是否与我的不同。

与其获取索引的 i-th 值,不如像这样构建 final_list :

final_list = [list_to_slice[indexes[i]:indexes[i+1]] for i in range(0,len(indexes)-1)]

使用itertools.pairwise:

>>> from itertools import pairwise
>>> for i, j in pairwise([0, 888, 1776, 2664, 3551, 4438]):
...     print(i, j)
...
0 888
888 1776
1776 2664
2664 3551
3551 4438

下一步是什么?我想你可以自己解决。