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 :
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