gpt4 book ai didi

python - 最高效的字典计数器

转载 作者:太空宇宙 更新时间:2023-11-03 18:33:35 27 4
gpt4 key购买 nike

我正在寻找通用“字典计数器”的更有效实现。目前,与集合相比,这个简单的函数产生更快的结果。计数器实现

def uniqueCounter(x):
dx = defaultdict(int)
for i in x:
dx[i] += 1
return dx

编辑:一些特征样本输入:

c1= zip(np.random.randint(0,2,200000),np.random.randint(0,2,200000))
c2= np.random.randint(0,2,200000)

c1:
uniqueCounter timing:
10 loops, best of 3: 61.1 ms per loop
collections.Counter timing:
10 loops, best of 3: 113 ms per loop

c2:
uniqueCounter timing: 10 loops, best of 3: 57 ms per loop
collections.Counter timing: 10 loops, best of 3: 120 ms per loop

最佳答案

尝试使用numpy.bincount

In [19]: Counter(c2)
Out[19]: Counter({1: 100226, 0: 99774})

In [20]: uniqueCounter(c2)
Out[20]: defaultdict(<type 'int'>, {0: 99774, 1: 100226})

In [21]: np.bincount(c2)
Out[21]: array([ 99774, 100226])

一些时间安排:

In [16]: %timeit np.bincount(c2)
1000 loops, best of 3: 2 ms per loop

In [17]: %timeit uniqueCounter(c2)
1 loops, best of 3: 161 ms per loop

In [18]: %timeit Counter(c2)
1 loops, best of 3: 362 ms per loop

关于python - 最高效的字典计数器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21975079/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com