通过字符串循环时,将多个值添加到字典 [英] Adding more than one value to dictionary when looping through string
问题描述
仍然超新到Python 3,遇到一个问题...我正在尝试创建一个函数,它返回一个字典,其中键是每个单词的长度,值是字符串中的单词。
Still super new to Python 3 and have encountered a problem... I am trying to create a function which returns a dictionary with the keys being the length of each word and the values being the words in the string.
例如,如果我的字符串是:狗很快前进到公园,我的字典应该返回
{2 :['to'] 3:[''','run','the'],4:['dogs','park],7:['快速','转发']}
For example, if my string is: "The dogs run quickly forward to the park", my dictionary should return
{2: ['to'] 3: ['The', 'run', 'the'], 4: ['dogs', 'park], 7: ['quickly', 'forward']}
问题是当我循环浏览项目时,它只是在字符串中附加一个单词。
Problem is that when I loop through the items, it is only appending one of the words in the string.
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']}
有人可以指出我的方向吗?也许不能自由地给我答案,但是下面我需要看一下将缺少的单词添加到列表中。我认为将它们附加到列表中会做到这一点,但不是这样。
Can someone point me in the right direction? Perhaps not giving me the answer freely, but what do I need to look at next in terms of adding the missing words to the list. I thought that appending them to the list would do it, but it's not.
谢谢!
推荐答案
这将解决您的所有问题:
This will solve all your problems:
def word_len_dict(my_string):
input_list = my_string.split(" ")
unique_set = set()
dictionary = {}
for item in input_list:
word = item.lower()
if word not in unique_set:
unique_set.add(word)
key = len(word)
if key not in dictionary:
dictionary[key] = []
dictionary[key].append(word)
return dictionary
您每次遇到时都会擦除dict条目一个新词还有一些有效的问题(在成长期间搜索成员名单,为O(n)任务产生O(n ** 2)个算法。更换成员资格考试清单成员资格考试更正了效率问题。
You were wiping dict entries each time you encountered a new word. There were also some efficiencly problems (searching a list for membership while growing it resulted in an O(n**2) algorithm for an O(n) task). Replacing the list membership test with a set membership test corrected the efficiency problem.
为您的示例句子提供正确的输出:
It gives the correct output for your sample sentence:
>>> print(word_len_dict("The dogs run quickly forward to the park"))
{2: ['to'], 3: ['the', 'run'], 4: ['dogs', 'park'], 7: ['quickly', 'forward']}
我注意到其他一些发布的解决方案无法将单词映射为小写和/或无法删除重复的内容,这显然是您想要的。
I noticed some of the other posted solutions are failing to map words to lowercase and/or failing to remove duplicates, which you clearly wanted.
这篇关于通过字符串循环时,将多个值添加到字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!