First, use dict statistics

Loop through the element of an iterable, making it the key of the dictionary if it is not present, and assigning the key to 1 or incrementing the value of the element if it is present.

lists = ['a'.'a'.'b'.1.2.3.1]
count_dist = dict(a)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}
Copy the code

Second, use collections.defaultdict statistics

Defaultdict (parameter) takes a type argument, such as int, float, STR, and so on.

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

  • Defaultdict (int) – initialize to 0
  • Defaultdict (float) – initialize to 0.0
  • Defaultdict (STR) — initialize to “”
#Python Learning Exchange group: 531509025
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})
Copy the code

List count ()

The count() method counts the number of occurrences of an element in a list.

Use the syntax

# Use syntax
list.count(obj) # return times
Copy the code

Count the number of times a single object is counted

# count the number of times a single object is counted
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
Copy the code

Count the number of times each object in the 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
'''
Copy the code

Use set and list statistics

Use set to duplicate each element, then loop through each element to form a tuple with the corresponding number list.count(item).

#Python Learning Exchange group: 531509025
lists = ['a'.'a'.'b'.1.2.3.1]
count_set = set(lists)
print(count_set) # Set deweighting
# {1, 2, 3, 'b', 'a'}

count_list = list(a)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)]
Copy the code

The collections.counter method

Counter is a container object, and you can use the Counter class in the Collections module to count hash objects.

Counter is an unordered container type stored as a dictionary key-value pair, with the element as a key and its count as a value.

The count can be any Interger (including 0 and negative numbers).

The Counter() object also has several callable methods:

  • Most_common (n) – The TOP N most common elements
  • Elements — Get all keys converted by list
  • Update — Adds objects
  • Subtrct — Deletes the object
  • The subscript access a[‘xx’] – returns 0 if it does not exist
import collections
c = collections.Counter('helloworld')
Copy the code

Display the frequency of each element directly

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

usemost_common Display the most n elements

When multiple elements have the same number, they are arranged in random order.

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

Get with array subscript, like a dictionary

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

Statistical lists (as long as the objects in the list are hashable)

import collections
x = [1.2.3.4.5.6.7.8.1.8.8.8.4.3.5]
c = collections.Counter(x)
print(c)
# Counter({1: 2, 2: 1, 3: 2, 4: 2, 5: 2, 6: 1, 7: 1, 8: 4})
print(c.most_common(3))
# [(8, 4), (1, 2), (3, 2)]
dictc = dict(c) # Convert to dictionary
print(dictc)
# {1, 2, 2:1, 3, 2, 4, 2, 5:2, 6:1, 7:1, 8, 4}
Copy the code

If there are unhashalbe objects in the list, such as mutable lists, they cannot be counted.

Tuples can also be counted.

c = collections.Counter([[1.2]."hello".123.0.52])
# TypeError: unhashable type: 'list'
Copy the code

Once you have the Counter Counter object, you can do incremental updates on top of it.

Elements () — Returns an iterator

Elements are arranged in an indefinite order. Elements less than 1 are not included.

#Python Learning Exchange group: 531509025
import collections
c = collections.Counter(a=4,b=2,c=1)
print(c)
# Counter({'a': 4, 'b': 2, 'c': 1})

list(c.elements())
# ['a', 'a', 'a', 'a', 'b', 'b', 'c']
Copy the code

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())) # a
# ['a', 'a', 'b', 'c']

# Reduce elements
c.subtract(["a"."b"])
print(c)
# Counter({'a': 1, 'c': 1, 'b': 0})
print(list(c.elements()))
# ['a', 'c']
Copy the code

Update function – adds elements

The update function is very useful when doing incremental counting.

#Python Learning Exchange group: 531509025

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

c.update(["a"."d"])
print(c)
# Counter({'a': 3, 'b': 1, 'c': 1, 'd': 1})
print(list(c.elements()))
# ['a', 'a', 'a', 'b', 'c', 'd']
Copy the code

Del function — Delete key

When the count is 0, it does not mean that the element is deleted, and the element should be deleted using del.

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

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

del c["l"]
print(c)
# Counter({'o': 2, 'h': 1, 'e': 1, 'w': 1, 'r': 1, 'd': 0})
Copy the code