如何将一个列表分成多个小列表呢,对于 str
Python 提供了 partition
函数,但 list
没有,所以只能自己实现一个。
源码地址
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]]