我正在尝试完成这个练习,我必须返回一个字典,其中键是单词的长度,值是单词本身。
预期输出应该是这样的:
{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']}
最佳答案
对您的初始代码的一些评论
- 每次执行
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']}
关于Python:For循环在第一次迭代后停止向字典添加项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56301521/