可能重复:
How do you split a list into evenly sized chunks in Python?如何通过n个元素对python中的元素进行分组?
我想获得大小n个元素的组从列表L:
即:
[1,2,3,4,5,6,7,8,9] -> [[1,2,3], [4,5,6],[7,8,9]] where n is 3
可能重复:
How do you split a list into evenly sized chunks in Python?如何通过n个元素对python中的元素进行分组?
我想获得大小n个元素的组从列表L:
即:
[1,2,3,4,5,6,7,8,9] -> [[1,2,3], [4,5,6],[7,8,9]] where n is 3
见itertools文档底部的示例:http://docs.python.org/library/itertools.html?highlight=itertools#module-itertools
你想要“石斑鱼”方法,或类似的东西。
那么,蛮力答案是:
subList = [theList[n:n+N] for n in range(0, len(theList), N)]
其中N
是组大小(3你的情况):
>>> theList = 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]]
您可以使用石斑鱼从recipes迭代工具文档页面:
def grouper(n, iterable, fillvalue=None):
"grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx"
args = [iter(iterable)] * n
return izip_longest(fillvalue=fillvalue, *args)
我认为这是做到这一点的最好方法。然而,更有用的答案会链接到这里:http://stackoverflow.com/questions/434287/what-is-the-most-pythonic-way-to-iterate-over-a-list-in-chunks/434411# 434411,因为它包括一些讨论为什么这个工程。 – phooji 2011-02-14 23:38:54
如何
a = range(1,10)
n = 3
out = [a[k::k+n] for k in range(0,len(a),n)]
你测试过了吗?我不认为`[[1,4,7],[4],[7]]是所需的输出。 – 2011-02-14 23:22:04
answer = [L[3*i:(3*i)+3] for i in range((len(L)/3) +1)]
if not answer[-1]:
answer = answer[:-1]
重复:http://stackoverflow.com/questions/312443/how-do-you-split-a-list-into-uniformity-sized-chunk-in-python – phooji 2011-02-14 23:20:35