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?
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With