Splitting list into smaller lists of equal values

前端 未结 4 732
广开言路
广开言路 2021-01-15 18:22

I am looking to transform a list into smaller lists of equal values. An example I have is:

[\"a\", \"a\", \"a\", \"b\", \"b\", \"c\", \"c\", \"c\", \"c\"] 
<         


        
4条回答
  •  Happy的楠姐
    2021-01-15 18:51

    You could use itertools.groupby to solve the problem:

    >>> from itertools import groupby
    >>> [list(grp) for k, grp in groupby(["a", "a", "a", "b", "b", "c", "c", "c", "c"])]
    [['a', 'a', 'a'], ['b', 'b'], ['c', 'c', 'c', 'c']]
    

    It only groups consecutive equal elements but that seems enough in your case.

提交回复
热议问题