在python中计算某个值在字典中出现的次数?

ijxebb2r  于 2023-01-10  发布在  Python
关注(0)|答案(5)|浏览(142)

如果我有这样的东西:

D = {'a': 97, 'c': 0 , 'b':0,'e': 94, 'r': 97 , 'g':0}

例如,如果我想把“0”作为一个值来计数,而不必迭代整个列表,这可能吗?怎么做?

bjg7j2ky

bjg7j2ky1#

THIS ANSWER中所述,使用operator.countOf()是可行的方法,但您也可以在sum()函数中使用生成器,如下所示:

sum(value == 0 for value in D.values())
# Or the following which is more optimized 
sum(1 for v in D.values() if v == 0)

或者,作为一种稍微优化和功能性更强的方法,您可以通过将整数的__eq__方法作为构造函数传递来使用map函数。

sum(map((0).__eq__, D.values()))

基准:

In [15]: D = dict(zip(range(1000), range(1000)))

In [16]: %timeit sum(map((0).__eq__, D.values()))
49.6 µs ± 770 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)

In [17]: %timeit sum(v==0 for v in D.values())
60.9 µs ± 669 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)

In [18]: %timeit sum(1 for v in D.values() if v == 0)
30.2 µs ± 515 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)

In [19]: %timeit countOf(D.values(), 0)
16.8 µs ± 74.1 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

请注意,虽然在这种情况下使用map函数可能会更优化,但为了对这两种方法有一个更全面和一般的了解,您也应该对相对较大的数据集运行基准测试。然后,您可以根据所拥有的数据的结构和数量使用最合适的方法。

fivyi3re

fivyi3re2#

或者,使用collections.Counter

from collections import Counter
D = {'a': 97, 'c': 0 , 'b':0,'e': 94, 'r': 97 , 'g':0}

Counter(D.values())[0]
# 3
fkaflof6

fkaflof63#

您可以将其转换为列表进行计数,如下所示:

D = {'a': 97, 'c': 0 , 'b':0,'e': 94, 'r': 97 , 'g':0}
print(list(D.values()).count(0))
>>3

或者迭代这些值:

print(sum([1 for i in D.values() if i == 0]))
>>3
92dk7w1h

92dk7w1h4#

那是operator.countOf的工作。

countOf(D.values(), 0)

使用示例词典进行基准测试:

1537 ns  1540 ns  1542 ns  Counter(D.values())[0]
 791 ns   800 ns   802 ns  sum(value == 0 for value in D.values())
 694 ns   697 ns   717 ns  sum(map((0).__eq__, D.values()))
 680 ns   682 ns   689 ns  sum(1 for value in D.values() if value == 0)
 599 ns   599 ns   600 ns  sum([1 for i in D.values() if i == 0])
 368 ns   369 ns   375 ns  list(D.values()).count(0)
 229 ns   231 ns   231 ns  countOf(D.values(), 0)

验证码(在线试用!):

from timeit import repeat

setup = '''
from collections import Counter
from operator import countOf
D = {'a': 97, 'c': 0 , 'b':0,'e': 94, 'r': 97 , 'g':0}
'''

E = [
    'Counter(D.values())[0]',
    'sum(value == 0 for value in D.values())',
    'sum(map((0).__eq__, D.values()))',
    'sum(1 for value in D.values() if value == 0)',
    'sum([1 for i in D.values() if i == 0])',
    'list(D.values()).count(0)',
    'countOf(D.values(), 0)',
]

for _ in range(3):
    for e in E:
        number = 10 ** 5
        ts = sorted(repeat(e, setup, number=number))[:3]
        print(*('%4d ns ' % (t / number * 1e9) for t in ts), e)
    print()
jutyujz0

jutyujz05#

for i in hashmap:    
  print(Counter(hashmap.values())[hashmap[i]])

# In this way we can traverse & check the count with the help of Counter

相关问题