Splitting list into smaller lists of equal values

前端 未结 4 704
广开言路
广开言路 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 18:48

    You could use collections.Counter

    >>> lst = ["a", "a", "a", "b", "b", "c", "c", "c", "c"]
    >>> import collections
    >>> collections.Counter(lst).most_common()
    [('c', 4), ('a', 3), ('b', 2)]
    

    This works even when the values are not ordered and provides a very compact representation which then you could expand if needed into lists:

    >>> [[i]*n for i,n in collections.Counter(lst).most_common()]
    [['c', 'c', 'c', 'c'], ['a', 'a', 'a'], ['b', 'b']]
    

提交回复
热议问题