Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/288.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何制作计数器的子集?_Python_Data Structures_Python Collections - Fatal编程技术网

Python 如何制作计数器的子集?

Python 如何制作计数器的子集?,python,data-structures,python-collections,Python,Data Structures,Python Collections,我正在试验Python标准库集合 我有一个计数器 >>> c = Counter('achdnsdsdsdsdklaffaefhaew') >>> c Counter({'a': 4, 'c': 1, 'h': 2, 'd': 5, 'n': 1, 's': 4, 'k': 1, 'l': 1, 'f': 3,

我正在试验Python标准库集合

我有一个计数器

>>> c = Counter('achdnsdsdsdsdklaffaefhaew')
>>> c
Counter({'a': 4,
         'c': 1,
         'h': 2,
         'd': 5,
         'n': 1,
         's': 4,
         'k': 1,
         'l': 1,
         'f': 3,
         'e': 2,
         'w': 1})
我现在想要的是以某种方式得到这个计数器的子集作为另一个计数器对象。就这样,

>>> new_c = do_subset(c, [d,s,l,e,w])
>>> new_c
Counter({'d': 5,
         's': 4,
         'l': 1,
         'e': 2,
         'w': 1})

提前谢谢。

您可以访问
c
中的每个键,并将其值分配给新dict中的同一个键

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}

您只需构建一个字典并将其传递给计数器:

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})

如果你懒惰,你也可以传递
'dslew'
,因为字符串是可编辑的。@JayPatel很高兴我能帮上忙!如果我的回答有助于解决你的问题,请考虑。这是表示你的问题已经“解决”并感谢帮助你的人的惯常方式。OP想要的是一个计数器而不是一个命令。