如何统计字符串中指定不同字符的数量?以"true"为例
简洁统计指定字符总数量的实现方法
以下是几种针对你的需求(统计字符串"true"中t、r、u、e四个字符的总数)的简洁实现方式,以Python为例:
方法1:生成器表达式+sum函数(推荐,效率高)
利用集合的O(1)查找特性,结合生成器表达式快速累加符合条件的字符数量:
s = "true" targets = {'t', 'r', 'u', 'e'} total = sum(1 for c in s if c in targets) print(total) # 输出:4
这种方式无需额外导入模块,遍历一次字符串即可完成统计,性能最优。
方法2:str.count()循环求和
如果目标字符数量较少,直接循环调用字符串的count()方法累加结果也很直观:
s = "true" targets = ['t', 'r', 'u', 'e'] total = sum(s.count(char) for char in targets) print(total) # 输出:4
该写法代码简洁,适合快速实现简单需求。
方法3:collections.Counter(适合多场景复用)
如果后续需要多次查询不同字符组合的统计结果,使用Counter预统计所有字符的出现次数会更灵活:
from collections import Counter s = "true" targets = {'t', 'r', 'u', 'e'} char_counts = Counter(s) total = sum(char_counts.get(c, 0) for c in targets) print(total) # 输出:4
预统计后,后续的查询操作只需从Counter中取值,无需再次遍历原字符串。
内容的提问来源于stack exchange,提问作者Con1234
相关产品推荐
相关产品推荐

