In python, how can I split a long list into a list of lists wherever I come across '-'. 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']]
Many thanks in advance.
A list that occurs as an element of another list (which may ofcourse itself be an element of another list etc) is known as nested list.
Create Python Lists A list can also have another list as an item. This is called a nested list.
Tuples are identical to lists in all respects, except for the following properties: Tuples are defined by enclosing the elements in parentheses ( () ) instead of square brackets ( [] ). Tuples are immutable.
append() adds a list inside of a list. Lists are objects, and when you use . append() to add another list into a list, the new items will be added as a single object (item).
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']]
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']]
Here's one way to do it:
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
Basically, this finds the locations of the string '---' in the list and then slices the list accordingly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With