Python程序查找给定字符串中每个字符的出现
在本文中,我们将学习下面给出的问题陈述的解决方案。
问题陈述 -给我们一个字符串,我们需要找到给定字符串中每个字符的出现。
在这里,我们将讨论以下三种方法:L
方法1:蛮力方法
示例
test_str = "Nhooo"
#count dictionary
count_dict = {}
for i in test_str:
#for existing characters in the dictionary
if i in count_dict:
count_dict[i] += 1
#for new characters to be added
else:
count_dict[i] = 1
print ("Count of all characters in Nhooo is :\n "+
str(count_dict))输出结果
Count of all characters in Nhooo is :
{'T': 1, 'u': 1, 't': 2, 'o': 2, 'r': 1, 'i': 2, 'a': 1, 'l': 1, 's': 1, 'p': 1, 'n': 1}方法2:使用集合模块
示例
from collections import Counter
test_str = "Nhooo"
# using collections.Counter() we generate a dictionary
res = Counter(test_str)
print ("Count of all characters in Nhooo is :\n "+
str(dict(res)))输出结果
Count of all characters in Nhooo is :
{'T': 1, 'u': 1, 't': 2, 'o': 2, 'r': 1, 'i': 2, 'a': 1, 'l': 1, 's': 1, 'p': 1, 'n': 1}方法3:set()在Lambda表达式中使用
示例
test_str = "Nhooo"
# using set() to calculate unique characters in the given string
res = {i : test_str.count(i) for i in set(test_str)}
print ("Count of all characters in Nhooo is :\n "+
str(dict(res)))输出结果
Count of all characters in Nhooo is :
{'T': 1, 'u': 1, 't': 2, 'o': 2, 'r': 1, 'i': 2, 'a': 1, 'l': 1, 's': 1, 'p': 1, 'n': 1}结论
在本文中,我们了解了如何找到给定字符串中每个字符的出现。
热门推荐
1 训练狗狗基础
2 怎么训练狗狗笑
3 怎么训练狗狗卧下
4 上海狗狗训练基地
5 训练狗狗排便
6 狗狗基础训练
8 如何训练狗狗装死
9 狗狗站姿训练
10 狗狗训练用品
11 训练狗狗吧
12 狗狗要怎么训练
13 怎么训练狗狗玩球
14 训练狗狗唤回
15 狗狗训练躺下
16 狗狗训练指令
17 狗狗的训练技巧
18 狗狗不好训练