Home>Article>Backend Development> How to count in python
Several ways to count statistics in python
Use dictionary dict()(Recommended learning:Python video tutorial)
Loop through the elements in an iterable object. If the dictionary does not have the element, then use the element as the key of the dictionary and assign the key to 1. If it exists, set the element to 1. The value corresponding to the element is increased by 1.
lists = ['a','a','b',5,6,7,5] count_dict = dict() for item in lists: if item in count_dict: count_dict[item] += 1 else: count_dict[item] = 1
Use defaultdict()
defaultdict(parameter) can accept a type parameter, such as str, int, etc., but The type parameter passed in is not used to constrain the type of the value, let alone the type of the key, but to implement a value initialization 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', 5, 6, 7, 5] count_dict = defaultdict(int) for item in lists: count_dict[item] += 1
Use sets and lists
First use set to remove duplicates, and then loop through each element and the number of times each element corresponds to lists.count(item) to form a tuple and put it in the list
lists = ['a', 'a', 'b', 5, 6, 7, 5] count_set = set(lists) count_list = list() for item in count_set: count_list.append((item,lists.count(item))
More Python For related technical articles, please visit thePython Tutorialcolumn to learn!
The above is the detailed content of How to count in python. For more information, please follow other related articles on the PHP Chinese website!