How to count the frequency of the elements in an unordered list?

后端 未结 30 3237
时光说笑
时光说笑 2020-11-22 02:37

I need to find the frequency of elements in an unordered list

a = [1,1,1,1,2,2,2,2,3,3,4,5,5]

output->

b =         


        
30条回答
  •  南方客
    南方客 (楼主)
    2020-11-22 02:45

    For the record, a functional answer:

    >>> L = [1,1,1,1,2,2,2,2,3,3,4,5,5]
    >>> import functools
    >>> >>> functools.reduce(lambda acc, e: [v+(i==e) for i, v in enumerate(acc,1)] if e<=len(acc) else acc+[0 for _ in range(e-len(acc)-1)]+[1], L, [])
    [4, 4, 2, 1, 2]
    

    It's cleaner if you count zeroes too:

    >>> functools.reduce(lambda acc, e: [v+(i==e) for i, v in enumerate(acc)] if e

    An explanation:

    • we start with an empty acc list;
    • if the next element e of L is lower than the size of acc, we just update this element: v+(i==e) means v+1 if the index i of acc is the current element e, otherwise the previous value v;
    • if the next element e of L is greater or equals to the size of acc, we have to expand acc to host the new 1.

    The elements do not have to be sorted (itertools.groupby). You'll get weird results if you have negative numbers.

提交回复
热议问题