Divide a list into n sublists

4

I have the following list:

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

What I need is to split this list into n sublists, in this case you can not do it manually since n is going to be dynamic.

    
asked by anonymous 16.08.2016 / 23:12

2 answers

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

You can do this if you want 3 sublists:

n = 3
splited = [l[i::n] for i in range(n)]
print(splited) # [[0, 3, 6, 9, 12], [1, 4, 7, 10, 13], [2, 5, 8, 11, 14]]

If you want sublist elements to keep the sequence:

n = 3
splited = []
len_l = len(l)
for i in range(n):
    start = int(i*len_l/n)
    end = int((i+1)*len_l/n)
    splited.append(l[start:end])
print(splited) # [[0, 1, 2, 3, 4], [5, 6, 7, 8, 9], [10, 11, 12, 13, 14]]

Note that in this case the number of elements is divisible by n (3), if we had for example n = 4 the number of elements in each sublist would be different:

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

Or, following the second example:

splited = [[0, 1, 2], [3, 4, 5, 6], [7, 8, 9, 10], [11, 12, 13, 14]]
    
16.08.2016 / 23:13
2

You can use range :

def chunks(lista, n):
    for i in range(0, len(lista), n):
        yield lista[i:i + n]

l = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
print(list(chunks(l, 3)))

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

Font

An iteration is made over the list , specifying the third argument of range() , step , it is indicated to what step the iteration will be done, and when using yield the chunks will be returned while keeping the state from where it left off until the end of the iteration .

View demonstração

The above function will generate sublists from n elements in the example 3 . p>

To divide the list into n sublists , do so:

def chunks(lista, n):
    inicio = 0
    for i in range(n):
        final = inicio + len(lista[i::n])
        yield lista[inicio:final]
        inicio = final

l = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
print(list(chunks(l, 3)))

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

Font

To divide the list into n sublists the beginning and end is informed, the beginning is where you you want to start splitting, end is the amount of elements that each sublist will have, yield returns to sublist , and then assigned the variable inicio the value of final , which represents the position of the sublist , thus successively until the end of the iteration .

View demonstração

In the questions below you have some explanations about yield :

  • How useful is the reserved word yield ?
  • What is yield ?
  • 16.08.2016 / 23:26