python - 将列表拆分为单独的列表 [Python]

标签 python list

我有一个 list ,比如说

listx = [1, 2, 0, 5, 2, 3, 0, 3, 4, 2, 3, 5, 6, 0, 4]

如何将列表拆分为不包含 0 的连续部分?例如,此列表将分为

separated = [[1, 2], [5, 2, 3], [3, 4, 2, 3, 5, 6], [4]]

最佳答案

import itertools

In [69]: L = [1, 2, 0, 5, 2, 3, 0, 3, 4, 2, 3, 5, 6, 0, 4]

In [70]: [list(i[1]) for i in itertools.groupby(L, bool) if i[0]]
Out[70]: [[1, 2], [5, 2, 3], [3, 4, 2, 3, 5, 6], [4]]

关于python - 将列表拆分为单独的列表 [Python],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26822726/

相关文章:

Python合并npz文件

python - 我应该把 Celery 配置文件放在哪里?

python - 比较多个 Python 列表并合并 Levenshtein 相似性

Python 将元组列表的第二部分合并到字符串列表中

python - Python 中的 Perl qw 运算符?

python - 自定义 Django 字段不从查询返回 Enum 实例

python - 分区数如何影响 `wholeTextFiles` 和 `textFiles` ?

python - 在 Python 中检查多维列表

list - 返回 OCaml 中列表的第 n 个元素?

Python 3.5.2 游戏 : Box reveal animation