2 回答
TA贡献1826条经验 获得超6个赞
您可以简单地构建一个字典并将其传递给 Counter:
from collections import Counter
c = Counter({'a': 4,
'c': 1,
'h': 2,
'd': 5,
'n': 1,
's': 4,
'k': 1,
'l': 1,
'f': 3,
'e': 2,
'w': 1})
def do_subset(counter, lst):
return Counter({k: counter.get(k, 0) for k in lst})
result = do_subset(c, ['d', 's', 'l', 'e', 'w'])
print(result)
输出
Counter({'d': 5, 's': 4, 'e': 2, 'l': 1, 'w': 1})
TA贡献1851条经验 获得超3个赞
您可以访问每个键c并将其值分配给新字典中的相同键。
import collections
c = collections.Counter('achdnsdsdsdsdklaffaefhaew')
def subsetter(c, sub):
out = {}
for x in sub:
out[x] = c[x]
return collections.Counter(out)
subsetter(c, ["d","s","l","e","w"])
产量:
{'d': 5, 'e': 2, 'l': 1, 's': 4, 'w': 1}
添加回答
举报