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

The*_*One 26 python arrays grouping list

可能重复:
如何在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
Run Code Online (Sandbox Code Playgroud)

Mar*_*ers 23

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

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


Mik*_*one 22

好吧,蛮力的答案是:

subList = [theList[n:n+N] for n in range(0, len(theList), N)]
Run Code Online (Sandbox Code Playgroud)

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]]
Run Code Online (Sandbox Code Playgroud)

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

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

例:

>>> 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]]
Run Code Online (Sandbox Code Playgroud)


siz*_*erz 6

怎么样

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

  • 移除 `[]` 操作中额外的 `:`。这与我的第一部分的答案相同。 (2认同)

Ada*_*erg 5

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

您需要“石斑鱼”方法或类似方法。


归档时间:

查看次数:

41099 次

最近记录:

7 年,1 月 前