python返回以str为键的dict对象编号它以值的形式出现

2024-04-23 16:05:47 发布

您现在位置:Python中文网/ 问答频道 /正文

传递的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}$

我做错什么了?


Tags: key函数字符串innew参数get字母
2条回答

您试图通过使用dict/list理解和计数器轻松实现:

from collections import Counter

sentence = ' "west best worst first tapping snapping in a pest the straining singing forest living'

filtered_counter = {k: v for k, v in Counter([word[-3:] for word in sentence.lower().split() if len(word) > 2]).items() if v > 1}

首先,我们从标准库导入Counter类型,然后定义sentence。下一行是在降低整个句子并检查单词的长度是否至少为3之后,用每个单词的最后3个字母创建一个数组;它从中创建一个Counter对象,它生成一个dict样的对象,该对象枚举在数组中找到元素的次数;然后使用dict comprehension过滤输出,使其不包含不重复的单词。在

我将分解这一行,以便您能更好地看到它:

^{pr2}$
sentence = ' "west best worst first tapping snapping in a pest the straining singing forest living'

# Get the last 3 letters of each word if its length is greater than 3
words_gt3 = [word[-3:] for word in sentence.split() if len(word) >= 3]

# Count them (you can use collections.Counter() too)
out = {}
for w in words_gt3:
    if w not in out.keys():
        out[w] = 0
    out[w] += 1

# Filter non repeated words
out = dict([e for e in out.items() if e[1] > 1])
print out
# {'rst': 2, 'est': 4, 'ing': 5}

What am I doing wrong?

sentence.count():统计整个字符串(不是每个单词)中出现的次数。 因此'singing'.count('ing')将返回2。这就是为什么你计算6ing而不是{}。在

相关问题 更多 >