Search code examples
pythonlistgroup-bypython-itertools

python itertools groupby with filter usage


I have a list = [1, 2, 3, 3, 6, 8, 8, 10, 2, 5, 7, 7] I am trying to use groupby to convert it into

1
2
3
3
6
8,8
10
2,
5
7,7

Basically, anything greater then 6, I like to group them, otherwise I want to keep them ungrouped. Any hint on how I can do this with itertool groupby

My code currently:

for key, group in it.groupby(numbers, lambda x: x):
   f = list(group)
   if len(f) == 1:
      split_list.append(group[0])
   else:
      if (f[0] > 6):  #filter condition x>6
         for num in f: 
            split_list.append(num + 100)
       else:
         for num in f:
            split_list.append(num)

Solution

  • You can use itertools.groupby to group all elements greater than 6 and with groups of length greater than 1. All other elements remain ungrouped.

    If we want groups as standalone lists, we can use append. If we want groups flattened, we can use extend.

    from itertools import groupby
    
    lst = [1, 2, 3, 3, 6, 8, 8, 10, 2, 5, 7, 7]
    
    result = []
    for k, g in groupby(lst):
        group = list(g)
    
        if k > 6 and len(group) > 1:
            result.append(group)
        else:
            result.extend(group)
    
    print(result)
    

    Output:

    [1, 2, 3, 3, 6, [8, 8], 10, 2, 5, [7, 7]]