1

I have 15 elements in an array and I want to allocate each five of them to a block respectively. The elements are:

elements=["a",'b','c','d','e','f','g','h','i','j','k','l','m','n','o']

I wanted to say first 5 elements are belonged to block#1, second five are belonged to block#2 and so on. I need to do it in a loop structure as later on, I need to use the information of each block for a special task. As I am new to python I don't know how to write it. Any advice will be highly appreciated.

Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555
Julliette
  • 27
  • 1
  • 4
  • You know the elements in advance? Why don't you group them together hardcoded? – Willem Van Onsem Mar 12 '17 at 20:31
  • Yes , I knew these elements in advance, I read it from an excel file.I can't hardcode them because in reality they are 1500 elements and therefore I would have 300 blocks. I wrote 15 here, because if I learn how to write it in a loop for 15 elements I can dot it for 1500 as well. – Julliette Mar 12 '17 at 20:32

2 Answers2

2

You can simply use list comprehension for that:

result = [elements[i:i+5] for i in range(0,len(elements),5)]

which will generate:

>>> result
[['a', 'b', 'c', 'd', 'e'], ['f', 'g', 'h', 'i', 'j'], ['k', 'l', 'm', 'n', 'o']]

Or more generic:

def blockify(elements,n=5):
    return [elements[i:i+n] for i in range(0,len(elements),n)]

and then call it with blockify(elements,5).

What we do is we create a range that ranges from 0 to the len(elements) (length of the elements), and makes hops of 5 (or n in the generic case). Now for each of these steps, we add a slice elements[i:i+5] to the result.

Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555
0

Loop through all and divide index by 5 (floor division operator //) The result of dividing is number of group.

cymruu
  • 2,808
  • 2
  • 11
  • 23