开发者

How to find all groups in a list in python?

开发者 https://www.devze.com 2023-04-06 04:16 出处:网络
I have a list like this [0,0,1,1,1,0,0,0,1,1,0,0,1,1,1,1] and I want to group them and th开发者_运维知识库en find the length of each group. So the result will be like that:

I have a list like this

[0,0,1,1,1,0,0,0,1,1,0,0,1,1,1,1] 

and I want to group them and th开发者_运维知识库en find the length of each group. So the result will be like that:

[[2,0],[3,1].....[4,1]]


Use itertools.groupby:

>>> import itertools
>>> l =  [0,0,1,1,1,0,0,0,1,1,0,0,1,1,1,1]
>>> [(len(list(g)), k) for k,g in itertools.groupby(l)]
[(2, 0), (3, 1), (3, 0), (2, 1), (2, 0), (4, 1)]


In [7]: import itertools

In [8]: [[sum(1 for _ in g),v] for v,g in itertools.groupby(l)]
Out[8]: [[2, 0], [3, 1], [3, 0], [2, 1], [2, 0], [4, 1]]

Where l is your input list.

0

精彩评论

暂无评论...
验证码 换一张
取 消