从字符列表中计算字符串中的字符数

Nic*_*ton 5 python python-3.x

我正在尝试编写一个count(s, chars)带字符串s和字符列表的函数chars.该函数应计算给出的字母出现次数chars.它应该返回一个字典,其中键是字符列表中给出的字符chars.

例如:

In [1]: s = "Another test string with x and y but no capital h."
In [2]: count(s, ['A', 'a', 'z'])
Out[2]: 'A': 1, 'a': 3, 'z': 0
Run Code Online (Sandbox Code Playgroud)

我制作了一些代码,可以计算字符串的所有字符并返回它的字典:

return {i: s.count(i) for i in set(s)}
Run Code Online (Sandbox Code Playgroud)

但我不确定你将如何使用特定字符列表并返回字典...

Wil*_*sem 6

关于什么:

def count_chars(s,chars):
    return {c : s.count(c) for c in chars}
Run Code Online (Sandbox Code Playgroud)

产生:

$ python3
Python 3.5.2 (default, Nov 17 2016, 17:05:23) 
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> s = "Another test string with x and y but no capital h."
>>> def count_chars(s,chars):
...     return {c : s.count(c) for c in chars}
... 
>>> count_chars(s, ['A', 'a', 'z'])
{'z': 0, 'A': 1, 'a': 3}
Run Code Online (Sandbox Code Playgroud)

虽然这是相当低效的.可能更有效的方法是一步计数.您可以使用a Counter,然后保留有趣的字符:

from collections import Counter

def count_chars(s,chars):
    counter = Counter(s)
    return {c : counter.get(c,0) for c in chars}
Run Code Online (Sandbox Code Playgroud)