编写一个函数find_longest_word(wordList),它接受一个单词列表并返回列表中最长的单词.如果存在多个最长的单词(即,具有相同的长度),则它应该返回它们中的第一个(即,在列表中的其他之前出现的那个).
编写一个程序,要求用户输入一些由空格分隔的单词(全部在一行中).然后你的程序应该创建一个包含输入单词的列表(你可以在字符串中使用内置的split方法)并输出列表和最长的单词(使用上面的函数).
样品运行:
输入几个单词,我会发现最长的:
敏捷的棕色狐狸跳过了懒狗
输入的单词列表是:
['敏捷的棕色狐狸跳过了懒狗']
列表中最长的单词是:
快
我的代码
def find_longest_word():
lizt=[]
s = input("Please type a sentence and I will out put the longest word. ")
for word in s:
lizt.append(word)
x = max(s.split(), key=len)
print('')
print('The list of words entered is:')
print(lizt)
print(s.split())
print('')
print('The longest word is:')
print(x)
find_longest_word()
Run Code Online (Sandbox Code Playgroud)
for word in s:
lizt.append(word)
Run Code Online (Sandbox Code Playgroud)
这个循环是错误的.s是一个字符串,word in s将遍历每个字母s,而不是每个字母中的每个空格分隔的单词.你只需要使用.split(),你的变量lizt是不必要的.
你可以这样做:
lizt = []
for word in s.split():
lizt.append(word)
Run Code Online (Sandbox Code Playgroud)
但这只会导致lizt与...相同s.split().所以lizt = s.split()会更简单.
如果你真的想为此使用循环,你可以尝试放弃使用max并执行以下操作:
max_word, max_len = None, 0
for word in s.split():
if len(word) > max_len:
max_word, max_len = word, len(word)
Run Code Online (Sandbox Code Playgroud)
但它会更简单,更Python只使用split和max,而不必自己写一个明确的循环.