Python 实现列表切分

如何将一个列表分成多个小列表呢,对于 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]]
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容