深度阅读

How to count the occurrences of an element in a list in Python?

作者
作者
2023年08月22日
更新时间
9.79 分钟
阅读时间
0
阅读量

To count the occurrences of an element in a list in Python, you can use the count() method of the list object. Here’s an example:

my_list = [1, 2, 3, 1, 1, 4, 5, 2]
count_of_ones = my_list.count(1)
print(count_of_ones)

Output:

3

In this example, we define a list of numbers and then use the count() method to count the number of times the number 1 appears in the list. The resulting count is 3.

Alternatively, you can use the Counter class from the collections module to get a dictionary with the count of each element in the list. Here’s an example:

from collections import Counter

my_list = [1, 2, 3, 1, 1, 4, 5, 2]
counts = Counter(my_list)
print(counts)

Output:

Counter({1: 3, 2: 2, 3: 1, 4: 1, 5: 1})

In this example, we use the Counter class to get a dictionary with the count of each element in the list. The resulting dictionary shows that the number 1 appears 3 times, the number 2 appears twice, and so on.

相关标签

博客作者

热爱技术,乐于分享,持续学习。专注于Web开发、系统架构设计和人工智能领域。