I have a list of numerical values, for example my_list = [1,34,56,2,7,89,12,13,10,56,43,12,78,98,5,105,1,2] and a set of predefined groups:
group1 - values between 0 and 5,
group2 - values between 6 and 12,
group3 - values between 13 and 25,
group4 - values between 26 and 60,
group5 - values between 61 and inf,
I would like to obtain the following:
{1: [1,2,1,2,5],
2: [7,12,10,12],
3: [13],
4: [34,56,56,43],
5: [89,78,98,105]}
One way of doing it is to make a for loop and check the if-elif-else condition for each element, as below:
for element in my_list:
if 0 <= element <= 5:
groups[1].append(element)
elif 6 <= element <= 12:
groups[2].append(element)
elif ...
Is there any way to group the elements of the list which is faster and a little bit more elegant? The real my_list which I'm using is large, so any way to optimize would be great!