我正在尝试编写代码来获取这种形式的列表的子序列:
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]]
谢谢你。
连续子序列?寻呼 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)
isFalse
和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]]
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]]