可以使用切片操作符[:]来实现列表的切割。下面是一个示例代码:

def split_list(lst, indices):
    result = []
    start = 0
    for index in indices:
        result.append(lst[start:index])
        start = index
    result.append(lst[start:])
    return result

# 示例用法
my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
my_indices = [3, 6, 9]
result = split_list(my_list, my_indices)
print(result)

输出结果为:

[[1, 2, 3], [4, 5, 6], [7, 8, 9], [10]]

在示例中,split_list 函数接受一个列表 lst 和一个索引列表 indices 作为参数。它遍历索引列表,通过切片操作符将原始列表切割成多个子列表,然后将这些子列表添加到结果列表中。最后,将剩余的部分作为最后一个子列表添加到结果列表中。最终返回结果列表。

请注意,切割后的子列表不包含索引本身所指向的元素。例如,在示例中,索引列表 [3, 6, 9] 将原始列表切割成了 4 个子列表,分别是 [1, 2, 3][4, 5, 6][7, 8, 9][10]

Python 列表切片:按指定索引切割成多个子列表

原文地址: http://www.cveoy.top/t/topic/Iqn 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录