Split list into n chunks python

Use numpy

>>> import numpy
>>> x = range[25]
>>> l = numpy.array_split[numpy.array[x],6]

or

>>> import numpy
>>> x = numpy.arange[25]
>>> l = numpy.array_split[x,6];

You can also use numpy.split but that one throws in error if the length is not exactly divisible.

answered Apr 16, 2015 at 15:34

6

The solution[s] below have many advantages:

  • Uses generator to yield the result.
  • No imports.
  • Lists are balanced [you never end up with 4 lists of size 4 and one list of size 1 if you split a list of length 17 into 5].
def chunks[l, n]:
    """Yield n number of striped chunks from l."""
    for i in range[0, n]:
        yield l[i::n]

The code above produces the below output for l = range[16] and n = 6:

[0, 6, 12]
[1, 7, 13]
[2, 8, 14]
[3, 9, 15]
[4, 10]
[5, 11]

If you need the chunks to be sequential instead of striped use this:

def chunks[l, n]:
    """Yield n number of sequential chunks from l."""
    d, r = divmod[len[l], n]
    for i in range[n]:
        si = [d+1]*[i if i < r else r] + d*[0 if i < r else i - r]
        yield l[si:si+[d+1 if i < r else d]]

Which for l = range[16] and n = 6 produces:

[0, 1, 2]
[3, 4, 5]
[6, 7, 8]
[9, 10, 11]
[12, 13]
[14, 15]

See this stackoverflow link for more information on the advantages of generators.

answered Feb 21, 2019 at 8:47

1

If order doesn't matter:

def chunker_list[seq, size]:
    return [seq[i::size] for i in range[size]]

print[list[chunker_list[[1, 2, 3, 4, 5], 2]]]
>>> [[1, 3, 5], [2, 4]]

print[list[chunker_list[[1, 2, 3, 4, 5], 3]]]
>>> [[1, 4], [2, 5], [3]]

print[list[chunker_list[[1, 2, 3, 4, 5], 4]]]
>>> [[1, 5], [2], [3], [4]]

print[list[chunker_list[[1, 2, 3, 4, 5], 5]]]
>>> [[1], [2], [3], [4], [5]]

print[list[chunker_list[[1, 2, 3, 4, 5], 6]]]
>>> [[1], [2], [3], [4], [5], []]

answered May 11, 2017 at 17:29

more_itertools.divide is one approach to solve this problem:

import more_itertools as mit


iterable = range[1, 26]
[list[c] for c in mit.divide[6, iterable]]

Output

[[ 1,  2,  3,  4, 5],                       # remaining item
 [ 6,  7,  8,  9],
 [10, 11, 12, 13],
 [14, 15, 16, 17],
 [18, 19, 20, 21],
 [22, 23, 24, 25]]

As shown, if the iterable is not evenly divisible, the remaining items are distributed from the first to the last chunk.

See more about the more_itertools library here.

answered Aug 28, 2017 at 23:55

pylangpylang

36.3k11 gold badges120 silver badges110 bronze badges

My answer is to simply use python built-in Slice:

# Assume x is our list which we wish to slice
x = range[1, 26]
# Assume we want to slice it to 6 equal chunks
result = []
for i in range[0, len[x], 6]:
    slice_item = slice[i, i + 6, 1]
    result.append[x[slice_item]]

# Result would be equal to 

[[0,1,2,3,4,5], [6,7,8,9,10,11], [12,13,14,15,16,17],[18,19,20,21,22,23], [24, 25]]

rpb

2,7431 gold badge20 silver badges43 bronze badges

answered Aug 18, 2020 at 10:18

ArashsyhArashsyh

55910 silver badges16 bronze badges

1

Try this:

from __future__ import division

import math

def chunked[iterable, n]:
    """ Split iterable into ``n`` iterables of similar size

    Examples::
        >>> l = [1, 2, 3, 4]
        >>> list[chunked[l, 4]]
        [[1], [2], [3], [4]]

        >>> l = [1, 2, 3]
        >>> list[chunked[l, 4]]
        [[1], [2], [3], []]

        >>> l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
        >>> list[chunked[l, 4]]
        [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10]]

    """
    chunksize = int[math.ceil[len[iterable] / n]]
    return [iterable[i * chunksize:i * chunksize + chunksize]
            for i in range[n]]

It returns an iterator instead of a list for efficiency [I'm assuming you want to loop over the chunks], but you can replace that with a list comprehension if you want. When the number of items is not divisible by number of chunks, the last chunk is smaller than the others.

EDIT: Fixed second example to show that it doesn't handle one edge case

answered Jun 30, 2014 at 6:35

I came up with the following solution:

l = [x[i::n] for i in range[n]]

For example:

n = 6
x = list[range[26]]

l = [x[i::n] for i in range[n]]
print[l]

Output:

[[0, 6, 12, 18, 24], [1, 7, 13, 19, 25], [2, 8, 14, 20], [3, 9, 15, 21], [4, 10, 16, 22], [5, 11, 17, 23]]

As you can see, the output consists from n chunks, which have roughly the same number of elements.

How it works?

The trick is to use list slice step [the number after two semicolons] and to increment the offset of stepped slicing. First, it takes every n element starting from the first, then every n element starting from the second and so on. This completes the task.

answered Apr 19 at 10:30

Vlad HavriukVlad Havriuk

1,16114 silver badges26 bronze badges

Hint:

  • x is the string to be split.
  • k is number of chunks

    n = len[x]/k
    
    [x[i:i+n] for i in range[0, len[x], n]]
    

eyllanesc

226k18 gold badges130 silver badges198 bronze badges

answered Aug 17, 2018 at 17:48

MitendraMitendra

1,33016 silver badges10 bronze badges

Here take my 2 cents..

from math import ceil

size = 3
seq = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]

chunks = [
    seq[i * size:[i * size] + size]
    for i in range[ceil[len[seq] / size]]
]

# [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11]]

answered Aug 30, 2019 at 18:51

pista329pista329

6317 silver badges13 bronze badges

One way would be to make the last list uneven and the rest even. This can be done as follows:

>>> x
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25]
>>> m = len[x] // 6
>>> test = [x[i:i+m] for i in range[0, len[x], m]]
>>> test[-2:] = [test[-2] + test[-1]]
>>> test
[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16], [17, 18, 19, 20], [21, 22, 23, 24, 25]]

answered Jun 30, 2014 at 5:18

Sukrit KalraSukrit Kalra

31.5k7 gold badges65 silver badges70 bronze badges

4

Assuming you want to divide into n chunks:

n = 6
num = float[len[x]]/n
l = [ x [i:i + int[num]] for i in range[0, [n-1]*int[num], int[num]]]
l.append[x[[n-1]*int[num]:]]

This method simply divides the length of the list by the number of chunks and, in case the length is not a multiple of the number, adds the extra elements in the last list.

answered Jun 30, 2014 at 5:54

user2963623user2963623

2,2471 gold badge13 silver badges25 bronze badges

0

If you want to have the chunks as evenly sized as possible:

def chunk_ranges[items: int, chunks: int] -> List[Tuple[int, int]]:
    """
    Split the items by best effort into equally-sized chunks.
    
    If there are fewer items than chunks, each chunk contains an item and 
    there are fewer returned chunk indices than the argument `chunks`.

    :param items: number of items in the batch.
    :param chunks: number of chunks
    :return: list of [chunk begin inclusive, chunk end exclusive]
    """
    assert chunks > 0, \
        "Unexpected non-positive chunk count: {}".format[chunks]

    result = []  # type: List[Tuple[int, int]]
    if items >> 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]]
>>>

answered May 18, 2020 at 23:55

I would simply do [let's say you want n chunks]

import numpy as np

# convert x to numpy.ndarray
x = np.array[x]
l = np.array_split[x, n]

It works and it's only 2 lines.

Example:

# your list
x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25]
# amount of chunks you want
n = 6
x = np.array[x]
l = np.array_split[x, n]
print[l]

>> [array[[1, 2, 3, 4, 5]], array[[6, 7, 8, 9]], array[[10, 11, 12, 13]], array[[14, 15, 16, 17]], array[[18, 19, 20, 21]], array[[22, 23, 24, 25]]]

And if you want a list of list:

l = [list[elem] for elem in l]
print[l]

 >> [[1, 2, 3, 4, 5], [6, 7, 8, 9], [10, 11, 12, 13], [14, 15, 16, 17], [18, 19, 20, 21], [22, 23, 24, 25]]

answered Jan 27, 2021 at 16:16

2

x=[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25]
chunk = len[x]/6

l=[]
i=0
while i

Chủ Đề