Becay
Becay

Reputation: 103

Split list using a given item

I want to extract groups of elements between special elements '-break-'. And then store these groups into a new list.

This is the input list:

main_list = [ '-break-',
          'one',
          'two',
          '-break-',
          'three',
          '-break-',
          'four',
          'five',
          'six'
          '-break-',
          'seven',
          'eight',
          'nine',
          'ten'  
         ]

The output list should be:

new_list = [ ['one', 'two'],
         ['three'],
         ['four', 'five', 'six'],
         ['seven', 'eight', 'nine', 'ten'],
        ]

Upvotes: 1

Views: 34

Answers (2)

yatu
yatu

Reputation: 88305

Here's one approach using itertools.groupby:

from itertools import groupby
out = [[*v] for k,v in groupby(main_list, key= lambda x: x != '-break-') if k]

print(out)

[['one', 'two'],
 ['three'],
 ['four', 'five', 'six'],
 ['seven', 'eight', 'nine', 'ten']]

itertools.groupby groups together consecutive values that are equal. However when a key is provided, the same logic applies but using the outcome from the key function. In this case the key function will be generating the following values:

[x != '-break-' for x in main_list]
# [False, True, True, False, True, False, True, True, True, True, True, True, True]

So on each iteration we will be receiving a tuple consisting on the grouping key (either True or False) and a list with the corresponding values. So in order to keep only those where the grouping key is True, we only need to add if k as a condition.

Upvotes: 1

Matias Cicero
Matias Cicero

Reputation: 26331

Massive one-liner. It can probably be simplified:

new_list = [[y for y in x.split(',') if y] for x in ','.join(main_list).split('-break-') if x]

Here's a more clear view of the list comprehension:

[
    [
         y
         # Split all the elements by ","
         for y in x.split(',')
         # Filter out empty values
         if y
    ]
    # Join everything with "," and then split it by "-break-"
    for x in ','.join(main_list)
             .split('-break-') 
    # Filter out empty values
    if x
]

Upvotes: 0

Related Questions