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']]

Answers


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']

Need Your Help

Browser side Dust.js

javascript browser dust.js

I've been trying to put together a really simple example using Dust.js in the Browser. Although the docs are very good there doesn't seem to be much information on getting things configured in the ...

Applying a snapshot in Hyper-V WMI V2 from C#

c# wmi hyper-v

I am trying to replicate the following PowerShell in C#:

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.