Five Methods and Skills of Python Statistical Times

  • 2021-12-12 09:03:11
  • OfStack

Catalog 1. Statistic using dictionary dict 2. Statistic using collections. defaultdict 3. List count method 4. Statistic using set (set) and list (list) 5. collections. Counter method

1. Use the dictionary dict statistics

Loop through the element of an iterable object. If the element is not in the dictionary, let the element be the key of the dictionary, and assign the key to 1. If it exists, add 1 to the corresponding value of the element.


lists = ['a','a','b',1,2,3,1]
count_dist = dict()
for i in lists:
    if i in count_dist:
        count_dist[i] += 1
    else:
        count_dist[i] = 1
print(count_dist)
# {'a': 2, 'b': 1, 1: 2, 2: 1, 3: 1}

2. Statistics using collections. defaultdict

defaultdict(parameter) Accept 1 type parameter, for example: int, float, str, and so on.

The type parameter passed in is not used to constrain the type of value, let alone the type of key, but to initialize one kind of value when the key does not exist.


defaultdict(int) --  Initialized to 0
defaultdict(float) --  Initialized to 0.0
defaultdict(str) --  Initialized to ''
from collections import defaultdict
lists = ['a','a','b',1,2,3,1]
count_dict = defaultdict(int)
for i in lists:
    count_dict[i] += 1
print(count_dict)
# defaultdict(<class 'int'>, {'a': 2, 'b': 1, 1: 2, 2: 1, 3: 1})

3. List count method

count() Method is used to count the number of occurrences of an element in the list.

Use syntax:


#  Use syntax 
list.count(obj) #  Number of returns 


Count the number of times a single object:


#  Count the number of single objects 
aList = [123, 'abc', 'good', 'abc', 123]
print("Count for 123 :", aList.count(123))
print("Count for abc :", aList.count('abc'))
# Count for 123 : 2
# Count for abc : 2


Count the number of times every 1 object in List:


test = ["aaa","bbb","aaa","aaa","ccc","ccc","ddd","aaa","ddd","eee","ddd"]
print(test.count("aaa"))
# 4
print(test.count("bbb"))
# 1

test_result = []
for i in test:
    if i not in test_result:
        test_result.append(i)
print(test_result)

for i in test_result:
    print(f"{i}:{test.count(i)}")

'''
4
1
['aaa', 'bbb', 'ccc', 'ddd', 'eee']
aaa:4
bbb:1
ccc:2
ddd:3
eee:1
'''

4. Statistics using sets (set) and lists (list)

First use set De-duplication, and then loop every 1 element and the corresponding number of times list.count(item) To form tuples.


'''
 No one answers the problems encountered in study? Xiaobian created 1 A Python Learning and communication group: 531509025
 Looking for like-minded friends and helping each other , There are also good video learning tutorials and PDF E-books! 
'''
lists = ['a','a','b',1,2,3,1]
count_set = set(lists)
print(count_set) #  Set de-duplication 
# {1, 2, 3, 'b', 'a'}

count_list = list()
for i in count_set:
    count_list.append((i, lists.count(i)))
print(count_list)    
# [(1, 2), (2, 1), (3, 1), ('b', 1), ('a', 2)]

5. collections. Counter method

Counter Is a container object, using the collections In the module Counter Class can implement the hash Gets or sets the statistics for the.

Counter Is an unordered container type stored as a dictionary key-value pair with elements as key and counts as value.

The count value can be arbitrary Interger (Including 0 and negative numbers).

The Counter () object also has several methods that can be called:

count() 0 --TOP n elements with the highest frequency of occurrence elements --Get all keys through list conversion update --Add objects subtrct --Delete objects Subscript accesses a ['xx']--Returns 0 if not present

import collections
c = collections.Counter('helloworld')


Display the frequency of each element directly


print(c)
# Counter({'l': 3, 'o': 2, 'h': 1, 'e': 1, 'w': 1, 'r': 1, 'd': 1})


Use most_common Displays the most n elements

When the count values of multiple elements are the same, the arrangement is in no definite order.


print(c.most_common(3))
# [('l', 3), ('o', 2), ('h', 1)]


Use array subscript to get, similar to dictionary:


print("The number of 'o':", c['o'])
# The number of 'o': 2


Statistical list: (as long as the objects in the list can be hashed)


defaultdict(int) --  Initialized to 0
defaultdict(float) --  Initialized to 0.0
defaultdict(str) --  Initialized to ''
from collections import defaultdict
lists = ['a','a','b',1,2,3,1]
count_dict = defaultdict(int)
for i in lists:
    count_dict[i] += 1
print(count_dict)
# defaultdict(<class 'int'>, {'a': 2, 'b': 1, 1: 2, 2: 1, 3: 1})

0

If there is a unhashalbe Objects, such as mutable lists, cannot be counted.

Tuples can also be counted.


defaultdict(int) --  Initialized to 0
defaultdict(float) --  Initialized to 0.0
defaultdict(str) --  Initialized to ''
from collections import defaultdict
lists = ['a','a','b',1,2,3,1]
count_dict = defaultdict(int)
for i in lists:
    count_dict[i] += 1
print(count_dict)
# defaultdict(<class 'int'>, {'a': 2, 'b': 1, 1: 2, 2: 1, 3: 1})

1

Get Counter After the counter object, incremental updates can also be made on this basis.

elements() --Returns the iterator

Elements are arranged in no definite order, and elements with a number less than 1 are not included.


defaultdict(int) --  Initialized to 0
defaultdict(float) --  Initialized to 0.0
defaultdict(str) --  Initialized to ''
from collections import defaultdict
lists = ['a','a','b',1,2,3,1]
count_dict = defaultdict(int)
for i in lists:
    count_dict[i] += 1
print(count_dict)
# defaultdict(<class 'int'>, {'a': 2, 'b': 1, 1: 2, 2: 1, 3: 1})

2

subtract Function--Subtract elements


import collections
c = collections.Counter(["a","b","c","a"])
print(c)
# Counter({'a': 2, 'b': 1, 'c': 1})
print(list(c.elements())) #  Unfold 
# ['a', 'a', 'b', 'c']

#  Reduced element 
c.subtract(["a","b"])
print(c)
# Counter({'a': 1, 'c': 1, 'b': 0})
print(list(c.elements()))
# ['a', 'c']


update Function--Add Elements

At that time of incremental count, update Function is very useful.


defaultdict(int) --  Initialized to 0
defaultdict(float) --  Initialized to 0.0
defaultdict(str) --  Initialized to ''
from collections import defaultdict
lists = ['a','a','b',1,2,3,1]
count_dict = defaultdict(int)
for i in lists:
    count_dict[i] += 1
print(count_dict)
# defaultdict(<class 'int'>, {'a': 2, 'b': 1, 1: 2, 2: 1, 3: 1})

4

set 1 Function--Delete key

When the count value is 0, it does not mean that the element is deleted, and deleting the element should use set 1 .


defaultdict(int) --  Initialized to 0
defaultdict(float) --  Initialized to 0.0
defaultdict(str) --  Initialized to ''
from collections import defaultdict
lists = ['a','a','b',1,2,3,1]
count_dict = defaultdict(int)
for i in lists:
    count_dict[i] += 1
print(count_dict)
# defaultdict(<class 'int'>, {'a': 2, 'b': 1, 1: 2, 2: 1, 3: 1})

5

Related articles: