Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 计算变量中所有字母的出现次数,而不使用.Count_Python_Python 3.x_String_Text_Count - Fatal编程技术网

Python 计算变量中所有字母的出现次数,而不使用.Count

Python 计算变量中所有字母的出现次数,而不使用.Count,python,python-3.x,string,text,count,Python,Python 3.x,String,Text,Count,我一直在寻找一种方法来计算一封信在文本中出现的频率。我不允许使用任何模块(导入)和.count函数 例如: text = 'hello' 如何检查变量文本中每个字母出现的频率?初学者怎么做?也许通过使用函数 最终结果应如下所示: h:1,e:1,l:2,o:1 提前谢谢。你可以用字典。键是找到的字符,值是计数 >>> counts = {} >>> for c in text: ... if c not in counts: ...

我一直在寻找一种方法来计算一封信在文本中出现的频率。我不允许使用任何模块(导入)和.count函数

例如:

text = 'hello'
如何检查变量文本中每个字母出现的频率?初学者怎么做?也许通过使用函数

最终结果应如下所示:

h:1,e:1,l:2,o:1


提前谢谢。

你可以用字典。键是找到的字符,值是计数

>>> counts = {}
>>> for c in text:
...     if c not in counts:
...             counts[c] = 1
...     else:
...             counts[c] += 1
... 
>>> counts
{'h': 1, 'e': 1, 'l': 2, 'o': 1}

使用dict.get()清理代码。使用
counts[letter]=counts.get(letter,0)+1
而不是在循环中编写的内容。@BehzadShayegh-这是一个不错的选择,但就我个人而言,我喜欢更容易可视化的if/else表单。但这也许只是旁观者的眼睛。