数组的子序列不为零 [英] subsequences of an array that are not zero

查看:63
本文介绍了数组的子序列不为零的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写代码以获取这种形式的列表的子序列:

I am trying to write code to get the subsequences of a list of this form:

l = [240,200,160,4,0,0,0,0,4,4,4,0,0,0,1,1,1,1]

基本上,我需要获取不为零的子序列,因此需要以下形式的输出:

Basically, I need to get the subsequences that are not zero, so I need an output in this form:

output = [[255,200,160,4] , [4,4,4] , [1,1,1,1]]

谢谢.

推荐答案

连续的子序列?呼叫Groupby博士, itertools.groupby :

Contiguous subsequences? Paging Dr. Groupby, Dr. itertools.groupby:

>>> from itertools import groupby
>>> l = [240,200,160,4,0,0,0,0,4,4,4,0,0,0,1,1,1,1]
>>> [list(g) for k,g in groupby(l, lambda x: x != 0) if k]
[[240, 200, 160, 4], [4, 4, 4], [1, 1, 1, 1]]

,或者即使我们利用bool(0)Falsebool(any other integer)True的事实:

or even if we take advantage of the fact bool(0) is False and bool(any other integer) is True:

>>> [list(g) for k,g in groupby(l, bool) if k]
[[240, 200, 160, 4], [4, 4, 4], [1, 1, 1, 1]]

这篇关于数组的子序列不为零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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