4

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

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

理想情况下,解决方案可以同时al通用迭代一起工作,而不仅仅是在列表上。

4

2 回答 2

16

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]]
于 2012-11-16T11:39:06.647 回答
0
def split_lengths(a,l):
    resultList = []
    index=0

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

    retun resultList
于 2012-12-31T11:14:50.363 回答