Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 将列表拆分为不同长度的块_Python_List_Iterator - Fatal编程技术网

Python 将列表拆分为不同长度的块

Python 将列表拆分为不同长度的块,python,list,iterator,Python,List,Iterator,给定一个项目序列和另一个区块长度序列,如何将序列拆分为所需长度的区块 a = range(10) l = [3, 5, 2] split_lengths(a, l) == [[0, 1, 2], [3, 4, 5, 6, 7], [8, 9]] 理想情况下,解决方案可以将a和l作为通用的可重用项,而不仅仅是列表。用于列表的迭代器 In [12]: a = range(10) In [13]: b = iter(a) In [14]: from itertools import islice

给定一个项目序列和另一个区块长度序列,如何将序列拆分为所需长度的区块

a = range(10)
l = [3, 5, 2]
split_lengths(a, l) == [[0, 1, 2], [3, 4, 5, 6, 7], [8, 9]]
理想情况下,解决方案可以将
a
l
作为通用的可重用项,而不仅仅是列表。

用于列表的迭代器

In [12]: a = range(10)

In [13]: b = iter(a)

In [14]: from itertools import islice

In [15]: l = [3, 5, 2]

In [16]: [list(islice(b, x)) for x in l]
Out[16]: [[0, 1, 2], [3, 4, 5, 6, 7], [8, 9]]
或:

In [17]: b = iter(a)

In [18]: [[next(b) for _ in range(x)] for x in l]
Out[18]: [[0, 1, 2], [3, 4, 5, 6, 7], [8, 9]]
def split_lengths(a,l):
    resultList = []
    index=0

    for length in l:
        resultList.append(a[index : index + length])
        index = index + length

    retun resultList