在我的作业中,这个问题是要求我创建一个函数,在这个函数中,Python应该创建字典,以长字符串中的某个字母开头的字数是对称的。对称意味着该单词以一个字母开头,并以同一个字母结尾。我不需要此算法的帮助。我绝对知道我的确是对的,但是我只需要解决这个我无法弄清楚的关键错误。我写了d[word[0]] += 1
,它是以该特定字母开始的单词的频率加1。字典中的重要错误。如何让Python打印我的字典?
输出应该是这样的(使用我在下面提供的字符串): {'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))
谢谢!这是做到这一点的正确方法!有效!希望我将来不会通过使用你的代码(我从你那里得到的改正部分)得到关键错误, – Jorgan