List> List of Lists

In python, how can I split a long list into a list of lists, wherever I am? -. For example, how can I convert:

['1', 'a', 'b','---', '2','c','d','---','3','123','e','---','4'] 

to

 [['1', 'a', 'b'],['2','c','d'],['3','123','e'],['4']] 

Thank you very much in advance.

+6
python
source share
6 answers
 In [17]: import itertools # putter around 22 times In [39]: l=['1', 'a', 'b','---', '2','c','d','---','3','123','e','---','4'] In [40]: [list(g) for k,g in itertools.groupby(l,'---'.__ne__) if k] Out[40]: [['1', 'a', 'b'], ['2', 'c', 'd'], ['3', '123', 'e'], ['4']] 
+17
source share
 import itertools l = ['1', 'a', 'b','---', '2','c','d','---','3','123','e','---','4'] r = [] i = iter(l) while True: a = [x for x in itertools.takewhile(lambda x: x != '---', i)] if not a: break r.append(a) print r # [['1', 'a', 'b'], ['2', 'c', 'd'], ['3', '123', 'e'], ['4']] 
+4
source share
 import itertools a = ['1', 'a', 'b','---', '2','c','d','---','3','123','e','---','4'] b = [list(x[1]) for x in itertools.groupby(a, '---'.__eq__) if not x[0]] print b # or print(b) in Python 3 

Result

 [['1', 'a', 'b'], ['2', 'c', 'd'], ['3', '123', 'e'], ['4']] 
+1
source share

Here is one way to do this:

 lst=['1', 'a', 'b','---', '2','c','d','---','3','123','e','---','4'] indices=[-1]+[i for i,x in enumerate(lst) if x=='---']+[len(lst)] answer=[lst[indices[i-1]+1:indices[i]] for i in xrange(1,len(indices))] print answer 

This basically finds the location of the string β€œ---” in the list, and then cuts the list accordingly.

+1
source share

Here is a solution without itertools:

 def foo(input): output = [] currentGroup = [] for value in input: if '-' in value: #if we should break on this element currentGroup.append( value ) elif currentGroup: output.append( currentGroup ) currentGroup = [] if currentGroup: output.append(currentGroup) #appends the rest if not followed by separator return output print ( foo ( ['1', 'a', 'b','---', '2','c','d','---','3','123','e','---','4'] ) ) 
0
source share

Some time has passed since I did any python, so my syntax will be removed, but a simple loop is enough.

Follow the indices in two numbers

 firstList = ['1', 'a', 'b','---', '2','c','d','---','3','123','e','---','4'] listIndex = 0 itemIndex = 0 ii = 0 foreach item in firstList if(firstList[ii] == '---') listIndex = listIndex + 1 itemIndex = 0 ii = ii + 1 else secondList[listIndex][itemIndex] = firstList[ii] 
-one
source share

All Articles