Python中是否有与str.split等效的列表? [英] Is there a str.split equivalent for lists in Python?

查看:62
本文介绍了Python中是否有与str.split等效的列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个字符串,可以使用str.split方法将其在空白处分割:

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

"hello world!".split()

返回

['hello', 'world!']

如果我有类似的列表

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

是否有一个拆分方法,该方法将围绕None拆分并给我

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

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

如果没有内置方法,那么最Pythonic/优雅的方法是什么?

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

推荐答案

可以使用itertools生成简洁的解决方案:

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))

这篇关于Python中是否有与str.split等效的列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆