根据 Python 中的一组索引将列表拆分为子列表



我有一个类似于下面的列表

['a','b','c','d','e','f','g','h','i','j']

我想按索引列表分开

[1,4]

在这种情况下,它将是

[['a'],['b','c'],['d','e','f','g','h','i','j']]

[:1] =['a']
[1:4] = ['b','c']
[4:] = ['d','e','f','g','h','i','j']

情况 2:如果索引列表是

[0,6]

这将是

[[],['a','b','c','d','e'],['f','g','h','i','j']]

[:0] = []
[0:6] = ['a','b','c','d','e']
[6:] = ['f','g','h','i','j']

情况 3(如果索引是

[2,5,7]

这将是 [['a','b'],['c','d','e'],['h','i','j']] 如

[:2] =['a','b']
[2:5] = ['c','d','e']
[5:7] = ['f','g']
[7:] = ['h','i','j']

大致如下:

mylist = ['a','b','c','d','e','f','g','h','i','j']
myindex = [1,4]
[mylist[s:e] for s, e in zip([0]+myindex, myindex+[None])]

输出

[['a'], ['b', 'c', 'd'], ['e', 'f', 'g', 'h', 'i', 'j']]

此解决方案使用的是 numpy:

import numpy as np
def do_split(lst, slices):
return [sl.tolist()for sl in np.split(lst, slices)]
splits = do_split(a, [2,5,7])
Out[49]:
[['a', 'b'], ['c', 'd', 'e'], ['f', 'g'], ['h', 'i', 'j']]
a = [1,2,3,4,5,6,7,8,9,10]
newlist = []
divide = [2,5,7]
divide = [0]+divide+[len(a)]
for i in range(1,len(divide)):
newlist.append(a[divide[i-1]:divide[i]])
print(newlist)

输出:

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

我写这个函数是为了做你的要求

def splitter(_list, *args):
args_list = [0]
args_list += args
args_list.append(len(_list))
new_list = []
for i, arg in enumerate(args_list):
try:
new_list.append(_list[arg:args_list[i+1]])
except IndexError:
continue
return new_list

该函数可以像这样使用:

mylist = ['1', '2', '3', '4', '5', '6']
splitter(mylist, 2, 4)

其中返回:

[['1', '2'], ['3', '4'], ['5', '6']]

最新更新