我正在尝试编写代码来获取此表单列表的子序列:
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]]
谢谢。
答案 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)
False
而bool(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]]