astex
astex

Reputation: 1055

Splitting a list of lists and strings by a string

Is there a convenient pythonic way to split a list by a search string (even if the list contains non-strings and have nested lists). For example, say I would like to split the following by ',':

[[ 'something', ',', 'eh' ], ',', ['more'], ',', 'yet more', '|', 'even more' ]

This would become:

[[[ 'something', ',', 'eh' ]], [['more']], ['yet more', '|', 'even more']]

Upvotes: 2

Views: 110

Answers (2)

iruvar
iruvar

Reputation: 23394

Late to the party but FWIW, I think a combination of itertools.takewhile and iter with a sentinel value provides a quick solution

from itertools import takewhile

z = [[ 'something', ',', 'eh' ], ',', ['more'], ',',
  'yet more', '|', 'even more' ]
z = iter(z)
def provider():
  return list(takewhile(lambda x: x != ',', z))

for i in iter(provider, []):
  print i

... 
[['something', ',', 'eh']]
[['more']]
['yet more', '|', 'even more']

Upvotes: 0

root
root

Reputation: 80446

Take a look at itertools.groupby:

In [1]: from itertools import groupby

In [2]: lst = [[ 'something', ',', 'eh' ], ',', ['more'], ',', 'yet more', '|', 'even more' ]

In [3]: [list(group) for key, group in groupby(lst, lambda x: x!=',') if key]
Out[3]: [[['something', ',', 'eh']], [['more']], ['yet more', '|', 'even more']]

It basically splits items in your list into groups based on a criteria (item != ',') and the comprehension check if k filters out the groups that are False – that is the items that are equal to ','.

In [4]: for key, group in groupby(lst, lambda x: x!=','):
   ...:     print key, list(group)
   ...:     
True [['something', ',', 'eh']]
False [',']
True [['more']]
False [',']
True ['yet more', '|', 'even more']

Upvotes: 7

Related Questions