For example, there is a list
L=[1,1,-1,2,3,22,34,32,2,-3,34,22,-5]
How many times each element appears in the statistics list
Way One:
Turn the list into a dictionary dict, the dictionary key corresponds to each element in the list, and value represents the number of occurrences of each element.
D=dict.fromkeys (l,0) #两个参数, the first parameter is the corresponding list, and the second parameter sets the default value=0 for Dict.
Then, traversing each element in the list, the element is encountered in the Dict, and value is added 1.
For X in L:
D[l]+=1
Print (d)
Way two:
Take advantage of the counter subclass of the collection.
From collections Import Counter
C=counter (L) #直接把列表l传入Counter, returns a dict, the key in this dict corresponds to each element in the set, and value represents the number of occurrences of this element in the collection
Print (C.most_common (3)) #Counter类的most_common () method returns a value from a large to a small list, returning n most common elements The list and its number.
Python learning-the frequency with which elements appear in a statistical sequence (number of times)