如何在 Python 列表中统计对象的总出现次数?
列表是 Python 提供的最常用的数据结构之一。Python 中的列表是一种可变的数据结构,它具有元素的有序序列。以下是整数列表的示例:
示例
以下是一个整数列表。
lis= [1,2,7,5,9,1,4,8,10,1] print(lis)
输出
如果执行上面的代码片段,将会产生以下输出。
[1, 2, 7, 5, 9, 1, 4, 8, 10, 1]
在本文中,我们将讨论如何在 Python 列表中查找对象的总出现次数。对于上面的示例,数字 1 出现了 3 次。
Python 包含几种方法来计算列表项出现的次数。
使用循环
在这种方法中,我们使用传统方法,迭代循环并使用计数器变量来计算项目的出现次数。
示例
在下面的示例中,我们从用户那里获取输入并计算所需元素的出现次数。
def count_occurrence(lst, x): count = 0 for item in lst: if (item == x): count = count + 1 return count lst =[] n = int(input("Enter number of elements and the elements: ")) for i in range(n): item = int(input()) lst.append(item) x = int(input("Enter the number whose count you want to find in the list: ")) y = count_occurrence(lst,x) print('The element %s appears %s times in the list'%(x,y))
输出
上述代码的输出如下。
Enter number of elements and the elements: 8 2 4 1 3 2 5 2 9 Enter the number whose count you want to find in the list: 2 The element 2 appears 3 times in the list
使用列表 count() 方法
count() 方法计算元素在列表中出现的次数。在这种方法中,我们使用 Python 的 count() 方法来计算列表中元素的出现次数。此方法计算给定列表元素的总出现次数。
语法
count() 方法的语法如下所示。
list.count(ele)
其中,ele 是要计数的元素。
示例
在下面的示例中,我们使用 count() 方法计算元音列表中 ‘i’ 出现的次数。
vowels = ['a', 'e', 'i', 'o', 'i', 'u', 'i', 'o', 'e', 'a'] count = vowels.count('i') print("The count is" ,count)
输出
上述代码的输出如下。
The count is 3
使用 counter() 方法
这是另一种计算列表中元素出现次数的方法。counter 方法提供一个字典,其中包含所有元素出现的次数作为键值对,其中键是元素,值是它出现的次数。我们需要从 collections 中导入 Counter 模块。
示例
在这个例子中,我们使用 counter() 方法来计算列表中元素的出现次数。
from collections import Counter l = [1,2,7,5,9,1,4,8,10,1] x = 1 d = Counter(l) print('{} has occurred {} times'.format(x, d[x]))
输出
上述代码的输出如下。
1 has occurred 3 times
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP