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

新手上路,请多包涵

我正在尝试编写一个函数 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

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

 return {i: s.count(i) for i in set(s)}

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

原文由 Nick Charlton 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 398
1 个回答

关于什么:

 def count_chars(s,chars):
    return {c : s.count(c) for c in chars}

生成:

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

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

 from collections import Counter

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

原文由 Willem Van Onsem 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题