Python 程序用于查找给定字符串中每个字符的出现次数
pythonserver side programmingprogramming更新于 2025/8/5 21:00:17
在本文中,我们将了解下面给出的问题陈述的解决方案。
问题陈述 − 给定一个字符串,我们需要查找给定字符串中每个字符的出现次数。
这里我们将讨论下面讨论的 3 种方法:L
方法 1 − 强力方法
示例
test_str = "Tutorialspoint"
#count 字典
count_dict = {}
for i in test_str:
#for 字典中的现有字符
if i in count_dict:
count_dict[i] += 1
#for 要添加的新字符
else:
count_dict[i] = 1
print ("Tutorialspoint 中所有字符的计数为 :\n "+
str(count_dict))
输出
Tutorialspoint 中所有字符的计数为 :
{'T': 1, 'u': 1, 't': 2, 'o': 2, 'r': 1, 'i': 2, 'a': 1, 'l': 1, 's': 1, 'p': 1, 'n': 1}
方法 2 − 使用 collections 模块
示例
from collections import Counter
test_str = "Tutorialspoint"
# 使用 collections.Counter() 我们生成一个字典
res = Counter(test_str)
print ("Tutorialspoint 中所有字符的数量为 :\n "+
str(dict(res)))
输出
Tutorialspoint 中所有字符的数量为 :
{'T': 1, 'u': 1, 't': 2, 'o': 2, 'r': 1, 'i': 2, 'a': 1, 'l': 1, 's': 1, 'p': 1, 'n': 1}
方法 3 − 在 lambda 表达式中使用 set()
示例
test_str = "Tutorialspoint"
# 使用 set() 计算给定字符串中的唯一字符
res = {i : test_str.count(i) for i in set(test_str)}
print ("Tutorialspoint 中所有字符的数量为 :\n "+
str(dict(res)))
输出
Tutorialspoint 中所有字符的数量为 :
{'T': 1, 'u': 1, 't': 2, 'o': 2, 'r': 1, 'i': 2, 'a': 1, 'l': 1, 's': 1, 'p': 1, 'n': 1}
结论
在本文中,我们了解了如何查找给定字符串中每个字符的出现情况。
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

