将列表分成N个长度大致相等的部分
将列表大致分为 个部分的最佳方法是什么?例如,如果列表包含7个元素并将其分为2部分,则我们希望一个部分包含3个元素,而另一部分应包含4个元素.
What is the best way to divide a list into roughly equal parts? For example, if the list has 7 elements and is split it into 2 parts, we want to get 3 elements in one part, and the other should have 4 elements.
我正在寻找类似even_split(L, n)
的东西,它将L
分解为n
个部分.
I'm looking for something like even_split(L, n)
that breaks L
into n
parts.
def chunks(L, n):
""" Yield successive n-sized chunks from L.
"""
for i in xrange(0, len(L), n):
yield L[i:i+n]
上面的代码给出了3个块,而不是3个块.我可以简单地转置(对此进行迭代,并取每列的第一个元素,将其称为第一部分,然后取其第二,然后将其放入第二部分,依此类推),但这会破坏项目的顺序.
The code above gives chunks of 3, rather than 3 chunks. I could simply transpose (iterate over this and take the first element of each column, call that part one, then take the second and put it in part two, etc), but that destroys the ordering of the items.
由于四舍五入错误,该代码已损坏.不要使用它!
assert len(chunkIt([1,2,3], 10)) == 10 # fails
这里是可行的:
Here's one that could work:
def chunkIt(seq, num):
avg = len(seq) / float(num)
out = []
last = 0.0
while last < len(seq):
out.append(seq[int(last):int(last + avg)])
last += avg
return out
测试:
>>> chunkIt(range(10), 3)
[[0, 1, 2], [3, 4, 5], [6, 7, 8, 9]]
>>> chunkIt(range(11), 3)
[[0, 1, 2], [3, 4, 5, 6], [7, 8, 9, 10]]
>>> chunkIt(range(12), 3)
[[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11]]