【问题标题】:Python: For loop stops adding items to a dictionary after first iterationPython:For循环在第一次迭代后停止向字典添加项目
【发布时间】:2019-05-25 03:46:51
【问题描述】:

我正在尝试完成这个练习,我必须返回一个字典,其中键是单词的长度,值是单词本身。

预期的输出应该是这样的:

{3: ['May', 'and'], 4: ['your'], 6: ['Monday', 'coffee', 'strong'], 2: ['be'], 5: ['short']} 

(可以按任何顺序)。但是,我不断得到一个输出,其中字典中的值列表不完整,例如:

{3: ['and'], 4: ['your'], 6: ['Monday'], 2: ['be'], 5: ['short']}

因为在使用 for 循环的第一次迭代后,它似乎停止向字典添加项目。

def get_word_len_dict(text):
    dictionary = {}
    word_list = text.split()
    for word in word_list:
        letter = len(word)
        dictionary[letter] = [word]

    return dictionary

def test_get_word_len_dict():
    text = "May your coffee be strong and your Monday be short"
    the_dict = get_word_len_dict(text)
    print(the_dict) #should print {3: ['May', 'and'], 4: ['your'], 6: ['Monday', 'coffee', 'strong'], 2: ['be'], 5: ['short']}

【问题讨论】:

    标签: python list dictionary for-loop


    【解决方案1】:

    初始代码中的一些 cmets

    • 每次执行dictionary[letter] = [word] 时,您都会创建一个元素列表。
    • 相反,您希望通过 dictionary[letter].append(word) 将每个单词附加到列表中。

    • 您还可以使用dict.setdefault 将字典的每个键实例化为一个空列表,并且仅在列表中不存在时才添加单词,以确保每个键的单词都是唯一的

    进行这些更改后,代码将起作用

    def get_word_len_dict(text):
    
        #Instantiate your dictionary
        dictionary = {}
        word_list = text.split()
    
        for word in word_list:
            letter = len(word)
    
            #Set default value of key as a list
            dictionary.setdefault(letter,[])
    
            #If the word is not present in the list, only then add it
            if word not in dictionary[letter]:
                dictionary[letter].append(word)
    
        return dictionary
    
    def test_get_word_len_dict():
        text = "May your coffee be strong and your Monday be short"
        the_dict = get_word_len_dict(text)
    
        print(the_dict)
    
    test_get_word_len_dict()
    

    输出将是

    {3: ['May', 'and'], 4: ['your'], 6: ['strong', 'coffee', 'Monday'], 2: ['be'], 5: ['short']}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-10-20
      • 1970-01-01
      • 2023-03-11
      • 1970-01-01
      • 2021-07-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多