使用预定义列表进行计数

Counting using a pre-defined list

我正在尝试使用预定义列表对巨大列表中的值进行计数。

要计算的预定义值列表:p = ['a', 'b', 'c']

要进行计数的巨大列表:h = ['a', 'c', 'd', 'c'.....]

我目前正在使用

count = []
for item in p:
   count.append(h.count(item))

Out: count = [1,0,2]

但是,如果 h 非常大,则此方法非常慢。有没有一种快速的 pythonic 方法可以做到这一点?我不能使用 collections Counter,因为它不会 return 我的值是 p 但不在 h.

中的值

只循环一次:

In [2]: h = ['a', 'c', 'd', 'c']

In [8]: p = ['a', 'b', 'c']

In [9]: c = {x:0 for x in p}

In [10]: for x in h:
    if x in c:
        c[x] += 1
   ....:         

In [11]: c
Out[11]: {'a': 1, 'b': 0, 'c': 2}

使用 p 的项作为键值 0 来初始化一个字典,然后遍历 h 并检查当前项是否在该字典中,如果是,则增加其值:

>>> p = ['a', 'b', 'c']
>>> h = ['a', 'c', 'd', 'c']
>>> c = dict.fromkeys(p, 0)
>>> for x in h:
...     if x in c:
...         c[x] += 1
...         
>>> c
{'a': 1, 'c': 2, 'b': 0}
# ...
>>> from operator import itemgetter
>>> itemgetter(*p)(c)
(1, 0, 2)

无论如何我都会使用 Counter 然后强制 Counter 表现得像你想要的那样。事实上,Counter 已经默认为它从未计算过的任何项目打印 0。

import collections

p = ['a', 'b', 'c']
h = ['a', 'c', 'd', 'c']

c = collections.Counter(h)
print c

for i in p:
  print i, c[i]

输出:

Counter({'a': 1, 'c': 2, 'd': 1})
a 1
b 0
c 2