如何在python中按n个元素对元素进行分组[duplicate]

wtlkbnrh  于 2023-01-16  发布在  Python
关注(0)|答案(5)|浏览(125)
    • 此问题在此处已有答案**:

How do I split a list into equally-sized chunks?(66个答案)
7个月前关闭。
给定一个列表[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]]

webghufk

webghufk1#

那么,蛮力的答案是:

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

pxyaymoc2#

您可以使用itertools文档中的方法中的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)
3pvhb19x

3pvhb19x3#

不如

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

cngwdvgl4#

参见itertools文档底部的示例:http://docs.python.org/library/itertools.html?highlight=itertools#module-itertools
你想要“石斑鱼”方法,或者类似的方法。

ebdffaop

ebdffaop5#

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

相关问题