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

时间:2012-11-16 11:36:22

标签: python list iterator

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

a = range(10)
l = [3, 5, 2]
split_lengths(a, l) == [[0, 1, 2], [3, 4, 5, 6, 7], [8, 9]]

理想情况下,解决方案适用于al作为常规迭代,而不仅仅是列表。

2 个答案:

答案 0 :(得分:14)

在列表的迭代器上使用itertools.islice

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

答案 1 :(得分:0)

def split_lengths(a,l):
    resultList = []
    index=0

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

    retun resultList