gpt4 book ai didi

python - 为什么这个 python 字符序列代码给出了意想不到的结果?

转载 作者:太空宇宙 更新时间:2023-11-04 02:00:08 24 4
gpt4 key购买 nike

我正在编写一个 python 程序来查找单词中的字符序列。但是程序给出了意想不到的结果。我找到了一个完美运行的类似类型的程序。对我来说,我认为这两个程序非常相似,但不知道为什么其中一个不起作用

  1. 不工作的程序:
# 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)
  1. 正在运行的程序:
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'))
  1. 第一个程序的输出是:

输入字符串:google.com

{'g': 1, 'c': 1, 'm': 1, 'o': 1, 'l': 1, '.': 1, 'e': 1}
  1. 第二个程序的输出是:

{'c': 1, 'e': 1, 'o': 3, 'g': 2, '.': 1, 'm': 1, 'l': 1}

以上是正确的输出。

现在是我心中的问题。

我。为什么第一个程序运行不正常?

二。这两个程序的意识形态是否不同?

最佳答案

实际上,您使用的 if 语句中存在一个小错误。看看下面修改后的程序。

Note: Also make sure not to use pre-defined data type names like dict as variable names. I have changed that to d here.

>>> d = {}
>>>
>>> string=input("Enter the string:").strip().lower()
Enter the string:google.com
>>>
>>> for letter in string:
... if letter not in d.keys():
... d[letter] = 1
... else:
... d[letter] = d[letter] + 1
...
>>> print(d)
{'g': 2, 'o': 3, 'l': 1, 'e': 1, '.': 1, 'c': 1, 'm': 1}
>>>

您还可以查看以下在终端上执行的语句。

keyd.keys() 进行比较将始终返回False因为 key 在这里是一个字符串,而 d.keys() 将始终是 dict_keys 类型的对象(Python3) 和一个 list (Python2)。

>>> d = {"k1": "v1", "k3": "v2", "k4": "Rishi"}
>>>
>>> d.keys()
dict_keys(['k1', 'k3', 'k4'])
>>>
>>> "k1" in d
True
>>>
>>> not "k1" in d
False
>>>
>>> "k1" == d.keys()
False
>>>
>>> "k1" not in d
False
>>>

您的 2 个问题的答案:

  1. 因为语句letter != dict.keys()总是 True所以键数没有增加。只需将其更改为 letter not in dict.keys() .最好使用 d代替 dict这样声明看起来像letter not in d.keys() .

  2. 两个程序的逻辑相同,即遍历字典,检查字典中是否存在键。如果不存在,则创建一个计数为 1 的新 key 否则将相关计数增加 1 .

非常感谢。

关于python - 为什么这个 python 字符序列代码给出了意想不到的结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55876284/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com