Fastest way to count number of occurrences in a Python list

前端 未结 5 1985
悲&欢浪女
悲&欢浪女 2020-11-30 03:29

I have a Python list and I want to know what\'s the quickest way to count the number of occurrences of the item, \'1\' in this list. In my actual case, the item

5条回答
  •  旧时难觅i
    2020-11-30 04:11

    By the use of Counter dictionary counting the occurrences of all element as well as most common element in python list with its occurrence value in most efficient way.

    If our python list is:-

    l=['1', '1', '1', '1', '1', '1', '2', '2', '2', '2', '7', '7', '7', '10', '10']
    

    To find occurrence of every items in the python list use following:-

    \>>from collections import Counter
    
    \>>c=Counter(l)
    
    \>>print c
    
    Counter({'1': 6, '2': 4, '7': 3, '10': 2})
    

    To find most/highest occurrence of items in the python list:-

    \>>k=c.most_common()
    
    \>>k
    
    [('1', 6), ('2', 4), ('7', 3), ('10', 2)]
    

    For Highest one:-

    \>>k[0][1]
    
    6
    

    For the item just use k[0][0]

    \>>k[0][0]
    
    '1'
    

    For nth highest item and its no of occurrence in the list use follow:-

    **for n=2 **

    \>>print k[n-1][0] # For item
    
    2
    
    \>>print k[n-1][1] # For value
    
    4
    

提交回复
热议问题