Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Split a list into multiple lists based on a subset of elements [duplicate]

I am trying to split a list that I have into individual lists whenever a specific character or a group of characters occur.

eg.

Main_list = [ 'abcd 1233','cdgfh3738','hryg21','**L**','gdyrhr657','abc31637','**R**','7473hrtfgf'...]

I want to break this list and save it into a sublist whenever I encounter an 'L' or an 'R'

Desired Result:

sublist_1 = ['abcd 1233','cdgfh3738','hryg21']
sublist_2 = ['gdyrhr657','abc31637']
sublist 3 = ['7473hrtfgf'...]

Is there a built in function or a quick way to do this ?

Edit: I do not want the delimiter to be in the list

like image 919
Polyhedronic Avatar asked Apr 19 '26 06:04

Polyhedronic


1 Answers

Use a dictionary for a variable number of variables.

In this case, you can use itertools.groupby to efficiently separate your lists:

L = ['abcd 1233','cdgfh3738','hryg21','**L**',
     'gdyrhr657','abc31637','**R**','7473hrtfgf']

from itertools import groupby

# define separator keys
def split_condition(x):
    return x in {'**L**', '**R**'}

# define groupby object
grouper = groupby(L, key=split_condition)

# convert to dictionary via enumerate
res = dict(enumerate((list(j) for i, j in grouper if not i), 1))

print(res)

{1: ['abcd 1233', 'cdgfh3738', 'hryg21'],
 2: ['gdyrhr657', 'abc31637'],
 3: ['7473hrtfgf']}
like image 186
jpp Avatar answered Apr 20 '26 19:04

jpp



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!