gpt4 book ai didi

python - 如何在 Python 中将列表切片为连续的非零整数组

转载 作者:太空狗 更新时间:2023-10-29 22:03:08 25 4
gpt4 key购买 nike

似乎无法在网上找到这方面的线索,也无法自己弄明白:

我将如何对列表进行切片,以便返回由连续非零整数组成的切片列表。即:

data = [3, 7, 4, 0, 1, 3, 7]

我想制作:

slices = [[3, 7, 4], [1, 3, 7]]

我尝试了各种遍历列表的方法,一直倾向于通过测试前后是否有 0 来让我知道相邻组何时开始和停止的生成器,但后来我有点难过.

最佳答案

import itertools
[ list(x[1]) for x in itertools.groupby(data, lambda x: x == 0) if not x[0] ]

关于python - 如何在 Python 中将列表切片为连续的非零整数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6760871/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com