我尝试使用预定义列表计算巨大列表中的值。
要计算的预定义值列表: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
,因为它不会为p
中的h
而不是{{1}}中的值返回0。
答案 0 :(得分:3)
无论如何我会使用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
答案 1 :(得分: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)
答案 2 :(得分:1)
只循环一次:
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}