mat*_*ots 5 python string list
如果我有一个字符串,我可以使用以下str.split
方法将其拆分为空格:
"hello world!".split()
Run Code Online (Sandbox Code Playgroud)
回报
['hello', 'world!']
Run Code Online (Sandbox Code Playgroud)
如果我有一个像这样的列表
['hey', 1, None, 2.0, 'string', 'another string', None, 3.0]
Run Code Online (Sandbox Code Playgroud)
是否有分裂方法会分裂None
并给我
[['hey', 1], [2.0, 'string', 'another string'], [3.0]]
Run Code Online (Sandbox Code Playgroud)
如果没有内置方法,最好的Pythonic /优雅方法是什么?
使用itertools可以生成简洁的解决方案:
groups = []
for k,g in itertools.groupby(input_list, lambda x: x is not None):
if k:
groups.append(list(g))
Run Code Online (Sandbox Code Playgroud)