一、功能介绍
功能:在指定下标处分割list,返回分割后的多个list
输入:
(1)一个被分割的list,如
a = [[1,1],[2,2],[3,3],[4,4],[5,5],[6,6],[7,7],[8,8],[9,9]]
(2)被分割list的指定下标
cut = [0,3,5]
输出:在a[0]、a[3]、a[5]处断开,形成一个包括3个子list的list
[[[1, 1]], [[2, 2], [3, 3], [4, 4]], [[5, 5], [6, 6]], [[7, 7], [8, 8], [9, 9]]]
二、代码实现
a = [[1,1],[2,2],[3,3],[4,4],[5,5],[6,6],[7,7],[8,8],[9,9]]
cut = [0,3,5]
martix = []
def list_slices(initial_list,cut):
left = initial_list
CumulativeLength = 0
for i in cut:
#获取 子列表
sub = left[:i+1-CumulativeLength] #list切片 左闭右开 故 +1
#添加子列表
martix.append(sub)
#print("martix:",martix)
#更新 剩余列表
left = left[i+1-CumulativeLength:]
#更新累计append的子列表长度
CumulativeLength += len(sub)
#print("left",left)
martix.append(left)
print("指定下标分割后的list:", martix) # [[[1, 1]], [[2, 2], [3, 3], [4, 4]], [[5, 5], [6, 6]], [[7, 7], [8, 8], [9, 9]]]
list_slices(a,cut)
说明:经笔者测试,此代码适同样适用于一维和多维list,只切割第一维度。