Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split Python list of strings into seperate lists based on character

I'm trying to figure out how to split the following list into separate lists based on a character in the list.

list = ['@', '2014', '00:03:01', 'Matt', '"login"', '0.01', '@', '2014', '02:06:12', 'Mary', '"login"', '0.01']

I want to create a list after every "@" symbol is introduced. For example, I would want the output to be the following:

NewList1 = ['@', '2014', '00:03:01', 'Matt', '"login"', '0.01'] 

NewList2 = ['@', '2014', '02:06:12', 'Mary', '"login"', '0.01']

Is this possible?

like image 413
taytortot Avatar asked Nov 29 '25 16:11

taytortot


1 Answers

You could use itertools.groupby:

import itertools as IT
import operator

seq = ['@', '2014', '00:03:01', 'Matt', '"login"', '0.01', '@', '2014', '02:06:12', 'Mary', '"login"', '0.01']

groups = (list(g) for k,g in IT.groupby(seq, lambda item: item=='@'))
print(list(IT.starmap(operator.add, IT.izip(*[groups]*2))))

prints

[['@', '2014', '00:03:01', 'Matt', '"login"', '0.01'], ['@', '2014', '02:06:12', 'Mary', '"login"', '0.01']]
like image 77
unutbu Avatar answered Dec 01 '25 04:12

unutbu