📌  相关文章
📜  Python|计算列表中某个元素的出现次数

📅  最后修改于: 2022-05-13 01:54:41.733000             🧑  作者: Mango

Python|计算列表中某个元素的出现次数

给定Python中的列表和数字 x,计算给定列表中 x 出现的次数。
例子:

Input : lst = [15, 6, 7, 10, 12, 20, 10, 28, 10]
         x = 10
Output : 3 
10 appears three times in given list.

Input : lst = [8, 6, 8, 10, 8, 20, 10, 8, 8]
        x = 16
Output : 0

方法1(简单方法)
如果在列表中找到所需的元素,我们会保持一个不断增加的计数器。

Python3
# Python code to count the number of occurrences
def countX(lst, x):
    count = 0
    for ele in lst:
        if (ele == x):
            count = count + 1
    return count
 
# Driver Code
lst = [8, 6, 8, 10, 8, 20, 10, 8, 8]
x = 8
print('{} has occurred {} times'.format(x, countX(lst, x)))


Python3
# Python code to count the number of occurrences
def countX(lst, x):
    return lst.count(x)
 
# Driver Code
lst = [8, 6, 8, 10, 8, 20, 10, 8, 8]
x = 8
print('{} has occurred {} times'.format(x, countX(lst, x)))


Python3
from collections import Counter
 
# declaring the list
l = [1, 1, 2, 2, 3, 3, 4, 4, 5, 5]
 
# driver program
x = 3
d = Counter(l)
print('{} has occurred {} times'.format(x, d[x]))


Output:
8 has occurred 5 times

方法2(使用count())
这个想法是使用列表方法 count() 来计算出现次数。

Python3

# Python code to count the number of occurrences
def countX(lst, x):
    return lst.count(x)
 
# Driver Code
lst = [8, 6, 8, 10, 8, 20, 10, 8, 8]
x = 8
print('{} has occurred {} times'.format(x, countX(lst, x)))
Output:
8 has occurred 5 times 

方法 2(使用 Counter())
Counter 方法返回一个字典,其中所有元素的出现作为键值对,其中 key 是元素,value 是该元素出现的次数。

Python3

from collections import Counter
 
# declaring the list
l = [1, 1, 2, 2, 3, 3, 4, 4, 5, 5]
 
# driver program
x = 3
d = Counter(l)
print('{} has occurred {} times'.format(x, d[x]))
Output:
3 has occurred 2 times