【发布时间】:2011-06-27 06:33:06
【问题描述】:
可能重复:
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
【问题讨论】:
标签: 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
【问题讨论】:
标签: python arrays list grouping
好吧,蛮力的答案是:
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]]
【讨论】:
您可以使用 itertools 文档中 recipes 中的 grouper 函数:
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)
【讨论】:
怎么样
a = range(1,10)
n = 3
out = [a[k:k+n] for k in range(0, len(a), n)]
【讨论】:
[[1, 4, 7], [4], [7]] 是所需的输出。
[]操作中多余的:。这与我的第一部分的答案相同。
查看 itertools 文档底部的示例:http://docs.python.org/library/itertools.html?highlight=itertools#module-itertools
你想要“grouper”方法,或者类似的东西。
【讨论】:
answer = [L[3*i:(3*i)+3] for i in range((len(L)/3) +1)]
if not answer[-1]:
answer = answer[:-1]
【讨论】: