[英]how do you write a program for function named makeWordLengthDict which takes a LIST of words as its only parameter, and returns a dictionary in python
I was trying to write the code for function named makeWordLengthDict which takes a LIST of words as its only parameter, and returns a dictionary that maps each word to the number of characters in that word.我试图为 function 编写名为 makeWordLengthDict 的代码,该代码将单词列表作为其唯一参数,并返回一个字典,该字典将每个单词映射到该单词中的字符数。 can anyone help me how to start it with?
谁能帮助我如何开始?
A simple dictionary comprehension would do this:一个简单的字典理解可以做到这一点:
def makeWordLengthDict(list_of_words):
return {i:len(i) for i in list_of_words}
If the function is called passing ["ball","cat"]
as the argument then the function will return: {'ball': 4, 'cat': 3}
如果 function 被称为传递
["ball","cat"]
作为参数,那么 function 将返回: {'ball': 4, 'cat': 3}
I thought I should post the second code before you ask.我想我应该在你问之前发布第二个代码。 So here you go buddy...
所以在这里你 go 哥们...
words_list = ["Apple", "Banana", "Ball", "Cat", "Bat", "Rat"] # Only Rat will be update in the Dictionary
def makeWordLengthDict(words):
keys = [len(word) for word in words]
words = [word for word in words]
return(keys, words)
keys, words = makeWordLengthDict(words_list)
# To access them accordingly.
for i in range(len(words_list)):
print(f"{keys[i]}: {words[i]}")
The code works but there is a problem with this concept.该代码有效,但这个概念存在问题。 If you have two words of the same length, only one of them will be updated to the dictionary(The last one only).
如果您有两个相同长度的单词,则只有其中一个会更新到字典中(仅最后一个)。 Because a dictionary can't have more than one item with the same key.
因为字典不能有多个具有相同键的项目。 Running the code I've provided will show you the problem.
运行我提供的代码将向您显示问题。 But you can do one thing if you find a length that is repeated, you can name them as 3a for another string in the list with 3 characters.
但是,如果您发现一个重复的长度,您可以做一件事,您可以将它们命名为 3a 用于列表中具有 3 个字符的另一个字符串。 But this might sound a bit inappropriate, so you can use two lists.
但这听起来可能有点不合适,因此您可以使用两个列表。 One will act as the key of the dictionary and the other one as the value for that key.
一个将作为字典的键,另一个作为该键的值。 Reply "Second Code" if you want the second one.
如果您想要第二个代码,请回复“第二个代码”。
words_list = ["Apple", "Banana", "Ball", "Cat", "Bat", "Rat"] # Only Rat will be update in the Dictionary
def makeWordLengthDict(words):
word_dict = {}
for word in words:
length = len(word)
word_dict.update({length: word})
return(word_dict)
print(makeWordLengthDict(words_list))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.