Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a str.split equivalent for lists in Python?

If I have a string, I can split it up around whitespace with the str.split method:

"hello world!".split()

returns

['hello', 'world!']

If I have a list like

['hey', 1, None, 2.0, 'string', 'another string', None, 3.0]

Is there a split method that will split around None and give me

[['hey', 1], [2.0, 'string', 'another string'], [3.0]]

If there is no built-in method, what would be the most Pythonic/elegant way to do it?

like image 736
math4tots Avatar asked Aug 19 '12 02:08

math4tots


1 Answers

A concise solution can be produced using itertools:

groups = []
for k,g in itertools.groupby(input_list, lambda x: x is not None):
    if k:
        groups.append(list(g))
like image 97
cmh Avatar answered Oct 08 '22 19:10

cmh