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

If I have a line, I can break it around a space using 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 separation method that will break into 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 this?

+4
source share
5 answers

A specific solution can be created using itertools:

 groups = [] for k,g in itertools.groupby(input_list, lambda x: x is not None): if k: groups.append(list(g)) 
+6
source

import itertools.groupby , then:

 list(list(g) for k,g in groupby(inputList, lambda x: x!=None) if k) 
+2
source

There is no built-in way to do this. Here is one possible implementation:

 def split_list_by_none(a_list): result = [] current_set = [] for item in a_list: if item is None: result.append(current_set) current_set = [] else: current_set.append(item) result.append(current_set) return result 
+1
source
 # Practicality beats purity final = [] row = [] for el in the_list: if el is None: if row: final.append(row) row = [] continue row.append(el) 
+1
source
 def splitNone(toSplit:[]): try: first = toSplit.index(None) yield toSplit[:first] for x in splitNone(toSplit[first+1:]): yield x except ValueError: yield toSplit 

 >>> list(splitNone(['hey', 1, None, 2.0, 'string', 'another string', None, 3.0])) [['hey', 1], [2.0, 'string', 'another string'], [3.0]] 
0
source

All Articles