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

后端 未结 30 3271
时光说笑
时光说笑 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 03:07

    Python 2.7+ introduces Dictionary Comprehension. Building the dictionary from the list will get you the count as well as get rid of duplicates.

    >>> a = [1,1,1,1,2,2,2,2,3,3,4,5,5]
    >>> d = {x:a.count(x) for x in a}
    >>> d
    {1: 4, 2: 4, 3: 2, 4: 1, 5: 2}
    >>> a, b = d.keys(), d.values()
    >>> a
    [1, 2, 3, 4, 5]
    >>> b
    [4, 4, 2, 1, 2]
    

提交回复
热议问题