在我的家庭作业中,这个问题是要求我建立一个函数,在这个函数中Python应该创建一个字典,说明在长字符串中以某个字母开头的单词有多少是对称的。对称的意思是这个词以一个字母开头,以同一个字母结尾。这方面的算法我不需要帮助。我当然知道我做得对,但是我只需要修复这个我无法理解的关键错误。我写了d[word[0]] += 1,这是为了增加以这个字母开头的单词的频率。
输出应该如下所示(使用下面提供的字符串):{'d': 1, 'i': 3, 't': 1}
t = '''The sun did not shine
it was too wet to play
so we sat in the house
all that cold cold wet day
I sat there with Sally
we sat there we two
and I said how I wish
we had something to do'''
def symmetry(text):
from collections import defaultdict
d = {}
wordList = text.split()
for word in wordList:
if word[0] == word[-1]:
d[word[0]] += 1
print(d)
print(symmetry(t))发布于 2016-11-19 19:38:37
您正在尝试增加尚未生成的条目的值,从而生成KeyError。当一个键还没有条目时,您可以使用get();将生成0的默认值(或您选择的任何其他值)。使用此方法,您将不需要defaultdict (尽管在某些情况下非常有用)。
def symmetry(text):
d = {}
wordList = text.split()
for word in wordList:
key = word[0]
if key == word[-1]:
d[key] = d.get(key, 0) + 1
print(d)
print(symmetry(t))样本输出
{'I': 3, 'd': 1, 't': 1}发布于 2016-11-19 19:37:07
虽然您导入了collections.defaultdict,但实际上从未使用过它。将d初始化为defaultdict(int),而不是{},这样就可以了。
def symmetry(text):
from collections import defaultdict
d = defaultdict(int)
wordList = text.split()
for word in wordList:
if word[0] == word[-1]:
d[word[0]] += 1
print(d)
print(symmetry(t))在以下方面的成果:
defaultdict(<class 'int'>, {'I': 3, 't': 1, 'd': 1})https://stackoverflow.com/questions/40697057
复制相似问题