繁体   English   中英

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

[英]Split a list into sublists based on a set of indexes in 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']]
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]]

此解决方案使用 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']]

我写了这个函数来完成你的要求

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']]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM