如何用n个元素对python中的元素进行分组?

时间:2011-02-14 23:13:13

标签: python arrays list grouping

  

可能重复:
  How do you split a list into evenly sized chunks in Python?

我想从列表l:

中获取n个元素的组

即:

[1,2,3,4,5,6,7,8,9] -> [[1,2,3], [4,5,6],[7,8,9]] where n is 3

5 个答案:

答案 0 :(得分:22)

您可以在itertools文档页面上使用recipes中的grouper:

def grouper(n, iterable, fillvalue=None):
    "grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx"
    args = [iter(iterable)] * n
    return izip_longest(fillvalue=fillvalue, *args)

答案 1 :(得分:21)

蛮力的回答是:

subList = [theList[n:n+N] for n in range(0, len(theList), N)]

其中N是组大小(在您的情况下为3):

>>> theList = list(range(10))
>>> N = 3
>>> subList = [theList[n:n+N] for n in range(0, len(theList), N)]
>>> subList
[[0, 1, 2], [3, 4, 5], [6, 7, 8], [9]]

如果您想要填充值,可以在列表理解之前执行此操作:

tempList = theList + [fill] * N
subList = [tempList[n:n+N] for n in range(0, len(theList), N)]

示例:

>>> fill = 99
>>> tempList = theList + [fill] * N
>>> subList = [tempList[n:n+N] for n in range(0, len(theList), N)]
>>> subList
[[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 99, 99]]

答案 2 :(得分:3)

请参阅itertools文档底部的示例:http://docs.python.org/library/itertools.html?highlight=itertools#module-itertools

你想要“石斑鱼”方法,或类似的东西。

答案 3 :(得分:2)

怎么样

a = range(1,10)
n = 3
out = [a[k:k+n] for k in range(0, len(a), n)]

答案 4 :(得分:0)

answer = [L[3*i:(3*i)+3] for i in range((len(L)/3) +1)]
if not answer[-1]:
    answer = answer[:-1]