【发布时间】:2019-09-16 11:30:56
【问题描述】:
我正在编写一个 python 程序来查找单词中的字符序列。但是该程序给出了意想不到的结果。 我发现了一个可以完美运行的类似类型的程序。 对我来说,我认为这两个程序非常相似,但不知道为什么其中一个不起作用
- 不工作的程序:
# Display the character sequence in a word
dict={}
string=input("Enter the string:").strip().lower()
for letter in string:
if letter !=dict.keys():
dict[letter]=1
else:
dict[letter]=dict[letter]+1
print(dict)
- 正在运行的程序:
def char_frequency(str1):
dict = {}
for n in str1:
keys = dict.keys()
if n in keys:
dict[n] += 1
else:
dict[n] = 1
return dict
print(char_frequency('google.com'))
- 第一个程序的输出是:
输入字符串:google.com
{'g': 1, 'c': 1, 'm': 1, 'o': 1, 'l': 1, '.': 1, 'e': 1}
- 第二个程序的输出是:
{'c': 1, 'e': 1, 'o': 3, 'g': 2, '.': 1, 'm': 1, 'l': 1}
以上是正确的输出。
现在是我脑海中的问题。
我。为什么第一个程序不能正常工作?
二。难道这两个方案的意识形态不同?
【问题讨论】:
-
旁注:这里的规范解决方案是
return collections.Counter(str1),因为计算可迭代次数是一个已解决的问题(在现代 Python 中,Counter有一个 C 加速器,它的运行速度比你可以编写的任何东西都快手)。
标签: python python-3.x dictionary frequency