如何在python中按n个元素分组元素
如何在python中按n个元素分组元素
这个问题已经有答案了:
给定一个列表[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]]
?
admin 更改状态以发布 2023年5月24日
您可以在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)
嗯,暴力解答是:
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]]