Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Divide a list into smaller lists depends on the length of length (even or odd)

I’m trying to write a code that could divide a list into smaller lists, as follows, I have a list and a value like that:

nb_classes = [1, 2, 3, 4, 5, 6, 7, 8, 9]
N = 3

I want to get smaller N lists depends on the length of nb_classes (if its even or odd).

If the length of nb_classes is odd, I want to have 3 small lists like that :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

nb_classes = [1, 2, 3, 4, 5, 6, 7, 8, 9]

list_1 = [1,2,3]
list_2 = [4,5,6]
list_3 = [7,8,9]

But, if the length of nb_classesis even, I want to have this result :

nb_classes = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

list_1 = [1,2,3,4]
list_2 = [5,6,7]
list_3 = [8,9,10]

Edit :

If the length of nb_classes is 11 for example, the result should be :

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

list_1 = [1,2,3,4]
list_2 = [5,6,7,8]
list_3 = [9,10,11]

Thank you.

>Solution :

So, I hardly tried to make it in one line. Here is what I ended up with

import math

nb_classes = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
N = 3

lists = [nb_classes[math.ceil(i): math.ceil(i + len(nb_classes) / N)] for i in (len(nb_classes) / N * j for j in range(len(nb_classes) // N))]

print(lists)  # [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11]]

But this may be a little bit complicated, you just need to ceil your indexes

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading