Sometimes we need to search and count the number (frequency) of specific elements in the list, so how to count? The following article will show you how to count the frequency of list elements in Python. I hope it will be helpful to you.
Method 1: Use Counter() set() List Comprehension
We You can use a combination of Counter() set() and List Comprehension to count the frequency of elements. The Counter() function performs grouping, and the set() function extracts different elements as keys of the dict and performs a list comprehension check on the list in which they appear.
Example:
# 列出元素的频率 from collections import Counter # 正在初始化列表 test_list = [[3, 5, 4], [6, 2, 4], [1, 3, 6]] # 输出原始列表 print("原始列表: " + str(test_list)) # 使用 Counter() + set() + list comprehension来列出元素的频率 res = dict(Counter(i for sub in test_list for i in set(sub))) # 输出结果 print("列表中元素的出现频率为:" + str(res))
Output:
##Method 2: Use Counter() itertools.chain.from_iterable () map() set()
set() function extracts the dictionary key formed by Counter(), map() function performs tasks for all sublists, and from_iterable() function uses Iterators perform tasks faster than List Comprehension. Example:# 列出元素的频率 from collections import Counter from itertools import chain # 正在初始化列表 test_list = [[2, 3, 4], [6, 2, 3], [1, 4, 6]] # 输出原始列表 print("原始列表: " + str(test_list)) #使用 Counter() + itertools.chain.from_iterable() + map() + set() 列出元素的频率 res = dict(Counter(chain.from_iterable(map(set, test_list)))) # 输出结果 print("列表中元素的出现频率为:" + str(res))
##Related video tutorial recommendation: "
Python Tutorial" The above is the entire content of this article, I hope it will be helpful to everyone's study. For more exciting content, you can pay attention to the relevant tutorial columns of the PHP Chinese website! ! !
The above is the detailed content of How to count the frequency of elements in a Python list? (code example). For more information, please follow other related articles on the PHP Chinese website!