如何按n个元素对列表进行分组,其中n在列表中定义

时间:2015-04-13 20:57:18

标签: python

我正在寻找更加“pythonic”的方式来做以下事情,或更简单的事情:

   lista = [2,4,6,8,3,4,6,2,1,4,23]
   splitby = [2,4,2,3]

预期输出,lista中的group元素by splitby:

grouped = [[2,4],[6,8,3,4],[6,2],[1,4,23]]

sum(splitby)将始终= len(lista)

以下是我的意见:

grouped = [[] for _ in xrange(len(splitby))]

for x in range(len(splitby)):
    for z in range(splitby[x]):
        grouped[x].append(lista[z + sum(splitby[0:x])])


>>> print grouped
[[2, 4], [6, 8, 3, 4], [6, 2], [1, 4, 23]]

使用groupby执行此操作的简单方法,例如?

1 个答案:

答案 0 :(得分:3)

我想我会使用itertools ......

from itertools import islice
ilista = iter(lista)
groups = [list(islice(ilista, 0, n)) for n in splitby]

而且,只是为了让自己相信它确实有效......这就是在行动中:

>>> from itertools import islice
>>> lista = [2,4,6,8,3,4,6,2,1,4,23]
>>> splitby = [2,4,2,3]
>>> ilista = iter(lista)
>>> groups = [list(islice(ilista, 0, n)) for n in splitby]
>>> print(groups)
[[2, 4], [6, 8, 3, 4], [6, 2], [1, 4, 23]]