Home > Article > Backend Development > Python method to count elements in a sequence
This article mainly introduces in detail how Python counts elements in a sequence. It has certain reference value. Interested friends can refer to it. I hope it can help everyone.
Question 1:
The highest number of occurrences in the random number sequence [12,5,8,7,8,9,4,8,5,...] 3 elements of , the number of times they appear
Question 2:
Perform word frequency statistics on the words of an English article and find out the 10 words with the highest number of occurrences Words, how many times do they occur?
The above problems are all about saving the results in the form of a dictionary
How to solve problem 1?
Method 1:
#!/usr/bin/python3 from random import randint def count_seq(data): # 初始化统计结果字典,data中的key作为结果字典的key,0作为每个key的初始值 result_c = dict.fromkeys(data, 0) # 循环data,对字典中中碰到的值进行 +1 ,循环完成后就是结果 for x in data: result_c[x] += 1 return result_c if __name__ == '__main__': # 生成20个随机数 data = [randint(0, 20) for _ in range(20)] print(data) # 结果 result_c = count_seq(data) for i in result_c: print(i, result_c[i])
Method 2:
Use Counter object under collections
#!/usr/bin/python3 from random import randint from collections import Counter def count_seq(data): # 创建Counter对象,并把打他传递进去 median_c = Counter(data) # 返回统计最大的3个数 return median_c.most_common(3) if __name__ == '__main__': # 生成20个随机数 data = [randint(0, 20) for _ in range(20)] print(data) # 结果 result_c = count_seq(data) print(result_c, dict(result_c))
How to solve problem 2?
import re from collections import Counter def count_words(): # 读取文件 with open('english_article', 'r', encoding='utf-8') as data: print() # 文件单词分割 data_list = re.split('\W+', data.read()) # 单词统计 words = Counter(data_list) # 取单词统计最大的10个值 return words.most_common(10) if __name__ == '__main__': result = count_words() print(result)
The above is the detailed content of Python method to count elements in a sequence. For more information, please follow other related articles on the PHP Chinese website!