给定一个项目序列和另一个块长度序列,如何将序列拆分为所需长度的块?
a = range(10)
l = [3, 5, 2]
split_lengths(a, l) == [[0, 1, 2], [3, 4, 5, 6, 7], [8, 9]]
理想情况下,解决方案可以同时a
与l
通用迭代一起工作,而不仅仅是在列表上。
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]]
def split_lengths(a,l):
resultList = []
index=0
for length in l:
resultList.append(a[index : index + length])
index = index + length
retun resultList