Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

a list > a list of lists

Tags:

python

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.

like image 500
DGT Avatar asked Jul 12 '10 20:07

DGT


People also ask

What is a nested list?

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.

What is a list of lists called in Python?

Create Python Lists A list can also have another list as an item. This is called a nested list.

Is a tuple a list of lists?

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.

How do I add a list to a list?

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).


3 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']]
like image 186
unutbu Avatar answered Oct 04 '22 01:10

unutbu


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']]
like image 42
Ignacio Vazquez-Abrams Avatar answered Oct 04 '22 03:10

Ignacio Vazquez-Abrams


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.

like image 43
MAK Avatar answered Oct 04 '22 02:10

MAK