栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

计算Python列表中出现次数的最快方法

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

计算Python列表中出现次数的最快方法

a = [‘1’, ‘1’, ‘1’, ‘1’, ‘1’, ‘1’, ‘2’, ‘2’, ‘2’, ‘2’, ‘7’, ‘7’, ‘7’, ‘10’, ‘10’]
print a.count(“1”)

它可能在C级别上进行了大量优化。

编辑:我随机生成一个大列表。

In [8]: len(a)Out[8]: 6339347In [9]: %timeit a.count("1")10 loops, best of 3: 86.4 ms per loop

编辑编辑:这可以通过collections.Counter完成。

a = Counter(your_list)print a['1']

在我的上一个计时示例中使用相同的列表

In [17]: %timeit Counter(a)['1']1 loops, best of 3: 1.52 s per loop

我的时间安排简单而又受许多不同因素的影响,但它为您提供了很好的性能线索。

这是一些分析

In [24]: profile.run("a.count('1')")         3 function calls in 0.091 seconds   Ordered by: standard name   ncalls  tottime  percall  cumtime  percall filename:lineno(function)        1    0.000    0.000    0.091    0.091 <string>:1(<module>)        1    0.091    0.091    0.091    0.091 {method 'count' of 'list' objects}        1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}In [25]: profile.run("b = Counter(a); b['1']")         6339356 function calls in 2.143 seconds   Ordered by: standard name   ncalls  tottime  percall  cumtime  percall filename:lineno(function)        1    0.000    0.000    2.143    2.143 <string>:1(<module>)        2    0.000    0.000    0.000    0.000 _weakrefset.py:68(__contains__)        1    0.000    0.000    0.000    0.000 abc.py:128(__instancecheck__)        1    0.000    0.000    2.143    2.143 collections.py:407(__init__)        1    1.788    1.788    2.143    2.143 collections.py:470(update)        1    0.000    0.000    0.000    0.000 {getattr}        1    0.000    0.000    0.000    0.000 {isinstance}        1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}  6339347    0.356    0.000    0.356    0.000 {method 'get' of 'dict' objects}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/638284.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号