
在这个例子中,我们将字符串"Today is a nice day!"分割成一个列表,每个单词作为一个元素。segmented_words
将会是一个包含每个单词的列表。
word_lengths
来保存每个单词的长度。word_lengths = {}
for word in segmented_words:
word_lengths[word] = len(word)
在这个例子中,我们使用for循环遍历了segmented_words
中的每个单词,并将每个单词作为字典word_lengths
的键,将其长度作为对应键的值。最后,word_lengths
将会是一个包含每个单词以及其对应长度的字典。
max
函数来实现这一步骤。longest_word = max(word_lengths, key=word_lengths.get)
在这个例子中,max
函数根据word_lengths
字典中每个键的值来找出最大值,并返回具有最大值的键。在这里,我们使用key
参数和word_lengths.get
函数来指定比较的值为字典中每个键对应的值。
print
函数来输出结果。print("The longest word is:", longest_word)
print("The length of the longest word is:", word_lengths[longest_word])
在这个例子中,我们使用print
函数输出了最长单词以及其长度。
综合起来,可以将以上代码整合为一个函数,并传入待分割的字符串作为参数:
def find_longest_word(sentence):
segmented_words = sentence.split()
word_lengths = {}
for word in segmented_words:
word_lengths[word] = len(word)
longest_word = max(word_lengths, key=word_lengths.get)
return longest_word, word_lengths[longest_word]
sentence = "Today is a nice day!"
longest_word, length = find_longest_word(sentence)
print("The longest word is:", longest_word)
print("The length of the longest word is:", length)
这样,我们就得到了最长单词以及其长度。希望上述解决方案能对你有所帮助。如有其他问题,请随时提问。
【相关推荐】