So I’m having a trouble. I’m working with python and I have a list that look like this example
['1', 'A', 'B', 'C', '1', 'D', '1', 'E', 'F', '1', 'G', 'H', 'I']
What I wanted is to make a list out of the elements between ‘1’
Like this
[['A', 'B', 'C'],['D'],['E', 'F'],['G', 'H', 'I']]
Anyone can give me an advice on how to achieve this?
5
One method would be to use itertools.groupby()
to split the list into consecutive groups based on whether they are equal to '1'
. As the docs note:
The key is a function computing a key value for each element.
If we set it to lambda x: x != '1'
then we can get the desired output by only including groups where key==True
.
import itertools
l = ['1', 'A', 'B', 'C', '1', 'D', '1', 'E', 'F', '1', 'G', 'H', 'I']
def split_list(l: list[str], split_by: str):
return [
list(group) for key, group in
itertools.groupby(l, lambda x: x != split_by) if key
]
split_list(l, '1')
# [['A', 'B', 'C'], ['D'], ['E', 'F'], ['G', 'H', 'I']]
You can test this ( for me it works ) :
def split_list(lst):
result = []
sublist = []
for item in lst:
if item == '1':
if sublist: # append the sublist to result if not empty
result.append(sublist)
sublist = [] # reset sublist
else:
sublist.append(item)
if sublist: # append the last sublist
result.append(sublist)
return result
# Example usage:
original_list = ['1', 'A', 'B', 'C', '1', 'D', '1', 'E', 'F', '1', 'G', 'H', 'I']
result_list = split_list(original_list)
print(result_list) # Output: [['A', 'B', 'C'], ['D'], ['E', 'F'], ['G', 'H', 'I']]