数组的子序列不为零

时间:2013-10-15 21:40:42

标签: python list

我正在尝试编写代码来获取此表单列表的子序列:

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

基本上,我需要得到非零的子序列,所以我需要这种形式的输出:

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

谢谢。

2 个答案:

答案 0 :(得分:10)

连续的后续序列?分配Dr.by博士,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>>> [list(g) for k,g in groupby(l, bool) if k] [[240, 200, 160, 4], [4, 4, 4], [1, 1, 1, 1]] 这一事实:

{{1}}

答案 1 :(得分:3)

In [117]: l = [240,200,160,4,0,0,0,0,4,4,4,0,0,0,1,1,1,1]

In [118]: [list(vals) for mask,vals in itertools.groupby(l, key=lambda n:n!=0) if mask]
Out[118]: [[240, 200, 160, 4], [4, 4, 4], [1, 1, 1, 1]]