如何將一個列表分成多個小列表呢,對于 str Python 提供了 partition 函數(shù),但 list 沒有,所以只能自己實現(xiàn)一個。
源碼地址
def partition(ls, size):
"""
Returns a new list with elements
of which is a list of certain size.
>>> partition([1, 2, 3, 4], 3)
[[1, 2, 3], [4]]
"""
return [ls[i:i+size] for i in range(0, len(ls), size)]
如果要分成 n 份,可以先計算出size的值為floor(len(ls)/n:
from math import floor
ls = [1, 2, 3, 4, 5]
n = 3
res = partition(ls, floor(len(ls)/n))
assert res == [[1, 2], [3, 4], [5]]