对Python 3仍然是超级新手,并且遇到了问题...我正在尝试创建一个函数,它返回一个字典,其中键是每个单词的长度,值是字符串中的单词。
例如,如果我的字符串是:“狗快速向前跑到公园”,我的字典应该返回{2: ['to'] 3: ['The', 'run', 'the'], 4: ['dogs', 'park], 7: ['quickly', 'forward']}
问题是,当我循环遍历这些项目时,它仅附加字符串中的单词之一。
def word_len_dict(my_string):
dictionary = {}
input_list = my_string.split(" ")
unique_list = []
for item in input_list:
if item.lower() not in unique_list:
unique_list.append(item.lower())
for word in unique_list:
dictionary[len(word)] = []
dictionary[len(word)].append(word)
return (dictionary)
print (word_len_dict("The dogs run quickly forward to the park"))
代码返回
{2: ['to'], 3: ['run'], 4: ['park'], 7: ['forward']}
有人能指出我正确的方向吗?也许不能自由地给我答案,但是在将缺失的单词添加到列表中时,我接下来需要考虑什么。我以为将它们添加到列表中就可以了,但事实并非如此。
谢谢你!