目录

Python 中的列表 (List) 类型是允许有重复项的,如何统计一个元素在列表中出现的次数?本文介绍三种方法:

  • 方法一:循环计数法
  • 方法二:list 类的 count 方法
  • 方法三:collections 包的 Counter 类

1. 方法一:循环计数法

循环计数法通过 for 循环遍历列表中的所有元素,每次循环比较当前元素与指定值是否相等,若相等则计数值加1。

代码

def get_count(a_list, value): 
    count = 0
    for element in a_list:
        if (element == value):
            count = count + 1
    return count

# 定义一个含有重复项的列表
my_list = [1,3,9,7,9,6,11,9,2,5]
count = get_count(my_list, 9)

print(f'数字9在列表中出现了{count}次')

输出结果

数字9在列表中出现了3次

2. 方法二:list 的 count 方法

list 的 count 方法用于统计元素出现的次数。

代码

# 定义一个含有重复项的列表
my_list = [1,3,9,7,9,6,11,9,2,5]
count = my_list.count(9)

print(f'数字9在列表中出现了{count}次')

输出结果

数字9在列表中出现了3次

3. 方法三:collections 包的 Counter 类

collections 包的 Counter 是一个容器类,可用于跟踪等效值增加的次数。

代码

from collections import Counter

# 定义一个含有重复项的列表
my_list = [1,3,9,7,9,6,11,9,2,5]
count = Counter(my_list)[9]

print(f'数字9在列表中出现了{count}次')

输出结果

数字9在列表中出现了3次

4. 性能比较

下面使用 timeit 库测试一下上面三种方法的性能,看看谁更快一些。

测试代码

import timeit

setup = """
from collections import Counter
my_list = [1,3,9,7,9,6,11,9,2,5]
def get_count(a_list, value):
    count = 0
    for element in a_list:
        if (element == value):
            count = count + 1
    return count
"""

method_1_test_code = """
count = get_count(my_list, 9)
"""

method_2_test_code = """
count = my_list.count(9)
"""

method_3_test_code = """
count = Counter(my_list)[9]
"""

method_1_taking_time = timeit.timeit(stmt=method_1_test_code, setup=setup, number=10)

method_2_taking_time = timeit.timeit(stmt=method_2_test_code, setup=setup, number=10)

method_3_taking_time = timeit.timeit(stmt=method_3_test_code, setup=setup, number=10)

print('“方法一 - 循环计数法”耗时: ' + str(method_1_taking_time))

print('“方法二 - list 的 count 方法”耗时: ' + str(method_2_taking_time))

print('“方法三 - collections 包的 Counter 类”耗时: ' + str(method_3_taking_time))

测试结果

“方法一 - 循环计数法”耗时: 3.8000289350748062e-06
“方法二 - list 的 count 方法”耗时: 1.400010660290718e-06
“方法三 - collections 包的 Counter 类”耗时: 2.489995677024126e-05

从测试结果可以看出:“方法三 - collections 包的 Counter 类”性能最好。

有关 Python 代码运行速度的测试方法可参见我的文章:如何测试 Python 代码的速度 - datetime, timeit

官方公众号

💯本站文章同步发表在官方公众号 ReadingHere,关注公众号您将在第一时间了解本站最新文章和资讯。

❤️欢迎您关注本站官方公众号 ReadingHere


版权声明

本文由ReadingHere原创,未经ReadingHere授权不得转载、摘编。已经授权使用的,应在授权范围内使用,并注明来源: www.readinghere.com。违反上述声明者,ReadingHere将追究其相关法律责任。


交流合作

如需交流咨询或商务合作请扫描下图微信二维码联系。