Python split list into n chunks

前端 未结 17 1495
情深已故
情深已故 2020-12-02 13:42

I know this question has been covered many times but my requirement is different.

I have a list like: range(1, 26). I want to divide this list into a fi

17条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-02 14:09

    This solution is based on the zip "grouper" pattern from the Python 3 docs. The small addition is that if N does not divide the list length evenly, all the extra items are placed into the first chunk.

    import itertools
    
    def segment_list(l, N):
        chunk_size, remainder = divmod(len(l), N)
        first, rest = l[:chunk_size + remainder], l[chunk_size + remainder:]
        return itertools.chain([first], zip(*[iter(rest)] * chunk_size))
    

    Example usage:

    >>> my_list = list(range(10))
    >>> segment_list(my_list, 2)
    [[0, 1, 2, 3, 4], (5, 6, 7, 8, 9)]
    >>> segment_list(my_list, 3)
    [[0, 1, 2, 3], (4, 5, 6), (7, 8, 9)]
    >>>
    

    The advantages of this solution are that it preserves the order of the original list, and is written in a functional style that lazily evaluates the list only once when called.

    Note that because it returns an iterator, the result can only be consumed once. If you want the convenience of a non-lazy list, you can wrap the result in list:

    >>> x = list(segment_list(my_list, 2))
    >>> x
    [[0, 1, 2, 3, 4], (5, 6, 7, 8, 9)]
    >>> x
    [[0, 1, 2, 3, 4], (5, 6, 7, 8, 9)]
    >>>
    

提交回复
热议问题