Python: batch list items in predefined groups

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 get 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 to do this is to create a for loop and check the if-elif-else condition for each element, as shown 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 a way to group list items that are faster and a bit more elegant? The real my_list I'm using is big, so any optimization method would be great!

+4
source share
1 answer

You can use bisect for this.

my_list , groups, .

>>> import bisect

>>> groups = [0, 6, 13, 26, 61]
>>> output = {}
>>> for x in my_list:
...     index = bisect.bisect_right(groups, x)
...     output.setdefault(index, []).append(x)
...

>>>
>>> output
{1: [1, 2, 5, 1, 2],
 4: [34, 56, 56, 43],
 2: [7, 12, 10, 12],
 5: [89, 78, 98, 105],
 3: [13]}
+6

Source: https://habr.com/ru/post/1682404/


All Articles