Splitting list into smaller lists of equal values

前端 未结 4 706
广开言路
广开言路 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条回答
  •  礼貌的吻别
    2021-01-15 19:03

    Another manner to have your desired output is by using defaultdict from collections module (best time using this approach was: ~= 0.02s same as using groupby):

    from collections import defaultdict
    a = ["a", "a", "a", "b", "b", "c", "c", "c", "c"]
    b = defaultdict(list)
    for k in a:
        b[k].append(k)
    
    >>> b 
    defaultdict(list,
                {'a': ['a', 'a', 'a'], 'b': ['b', 'b'], 'c': ['c', 'c', 'c', 'c']})
    

    So, what you have to do now is:

    list(b.values())
    >>> [['a', 'a', 'a'], ['b', 'b'], ['c', 'c', 'c', 'c']]
    

提交回复
热议问题