I would appreciate it if somebody could help me solve the following exercise.
(如果有人可以帮助我解决以下问题,我将不胜感激。)
Write a function that takes a string containing words separated by spaces and creates a dictionary where the keys correspond to the last characters of the words of the string, whilst the associated values correspond to the lists having the words ending in that character.
(编写一个函数,该函数接受包含用空格分隔的单词的字符串,并创建一个字典,其中的键对应于字符串中单词的最后一个字符,而关联的值对应于具有以该字符结尾的单词的列表。)
Furthermore, the lists must be lexicographically sorted
(此外,列表必须按字典顺序排序)
Example
(例)
string = "This will be an amazing experience"
Should return the following dictionary
(应该返回以下字典)
{'s':['This'], 'l':['will'], 'e':['be', 'experience'], 'n':['an'], 'g':['amazing']}
I have an idea of how the exercise should be solved.
(我对如何解决这项运动有一个想法。)
However, given that i am still a beginner in Python, i struggle. (但是,鉴于我仍然是Python的初学者,所以我很努力。)
The first thing i did is create an empty dictionary.
(我做的第一件事是创建一个空字典。)
Secondly, I converted the string of words into a list using the split method. (其次,我使用split方法将单词字符串转换为列表。)
Afterwards, i created another list that takes the last character of the words of the first list of strings and puts it into the new list. (之后,我创建了另一个列表,该列表采用第一个字符串列表中单词的最后一个字符,并将其放入新列表中。)
I used dict in order to put the elements of the second list as keys in my dictionary which works quite well.
(我使用dict以便将第二个列表的元素作为字典中的键,效果很好。)
The problem is i cannot put the list of corresponding words as values. (问题是我不能将相应单词的列表作为值。)
Here is my code:
(这是我的代码:)
def dictionary (string):
mydict = {}
mylist = string.split()
mylist2 = []
for word in mylist:
mylist2.append(word[-1])
mydict = dict((el,(word[-1] for word[-1] in mylist)) for el in mylist2)
return mydict
ask by alex108 translate from so 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…