传递的get_last_three_letters_dict()
函数
作为参数的文本字符串。函数首先转换参数
字符串转换为小写,然后返回dictionary对象,该对象具有:
remove_less_than_2
代码删除结果字典中的任何对,其中
最后三个字母只在文本的参数字符串中出现一次。
参数中任何单词的最后三个字母的键 长度大于2且
参数中的字数对应的值 以最后三个字母结尾的字符串。
到目前为止,我有这个:
sentence = 'west best worst first tapping snapping in a pest the straining singing forest living'
def remove_less_than_2(a_dict):
all_keys = list(a_dict.keys())
for key in all_keys:
if a_dict[key] == 1:
del a_dict[key]
def get_last_three_letters_dict(sentence):
new_dict = {}
new_sentence = sentence.lower()
new_sentence = sentence.split()
for word in new_sentence:
if len(word) > 2:
new_dict[word[-3:]] = sentence.count(word[-3:])
return new_dict
但它返回的值超出了它应该返回的值。
^{pr2}$我做错什么了?
您试图通过使用dict/list理解和计数器轻松实现:
首先,我们从标准库导入
Counter
类型,然后定义sentence
。下一行是在降低整个句子并检查单词的长度是否至少为3之后,用每个单词的最后3个字母创建一个数组;它从中创建一个Counter对象,它生成一个dict
样的对象,该对象枚举在数组中找到元素的次数;然后使用dict comprehension过滤输出,使其不包含不重复的单词。在我将分解这一行,以便您能更好地看到它:
^{pr2}$sentence.count()
:统计整个字符串(不是每个单词)中出现的次数。 因此'singing'.count('ing')
将返回2
。这就是为什么你计算6
ing
而不是{相关问题 更多 >
编程相关推荐