如何在Python中按n个元素分组

61 投票
5 回答
98188 浏览
提问于 2025-04-16 11:50

假设你有一个列表 [1,2,3,4,5,6,7,8,9,10,11,12],还有一个指定的分块大小(比如说是3),那么你想把这个列表分成几个小块,结果应该是 [[1,2,3],[4,5,6],[7,8,9],[10,11,12]] 这样的形式。

5 个回答

7

那这样怎么样

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

你可以使用itertools文档中的recipes里的grouper函数:

from itertools import zip_longest

def grouper(iterable, n, fillvalue=None):
    """Collect data into fixed-length chunks or blocks.

    >>> grouper('ABCDEFG', 3, 'x')
    ['ABC', 'DEF', 'Gxx']
    """
    args = [iter(iterable)] * n
    return zip_longest(*args, fillvalue=fillvalue)
61

好的,简单粗暴的答案是:

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

撰写回答