Fastest way to count number of occurrences in a Python list

前端 未结 5 1982
悲&欢浪女
悲&欢浪女 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条回答
  •  生来不讨喜
    2020-11-30 04:18

    You can use pandas, by transforming the list to a pd.Series then simply use .value_counts()

    import pandas as pd
    a = ['1', '1', '1', '1', '1', '1', '2', '2', '2', '2', '7', '7', '7', '10', '10']
    a_cnts = pd.Series(a).value_counts().to_dict()
    
    Input  >> a_cnts["1"], a_cnts["10"]
    Output >> (6, 2)
    

提交回复
热议问题