可能重複:
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