用Python统计列表中出现一次以上的数

 

>>> import collections

>>> a = list(range(1000000))
>>> a[100] = 1 #稍微改变一下列表
#
方法一
>>> b = filter(lambda x: a.count(x) > 1, a)
#方法二
>>> d = filter(lambda x: x[1] != 1,collections.Counter(a).items())

为什么方法一要比方法二慢得多呢?

方法一中的count()函数要O(n^2)的时间复杂度。

方法二加速的原因是什么呢?到底是怎么实现的?(值得深究)

帮助文档:

Dict subclass for counting hashable items. Sometimes called a bag
or multiset. Elements are stored as dictionary keys and their counts
are stored as dictionary values.

原来如此。

posted @ 2011-10-29 01:03  Let it be!  阅读(372)  评论(0编辑  收藏  举报