[英]Function to Find longest word in wordlist created from user input
Again, having trouble wrapping my head around an assignment. 再说一次,遇到麻烦困扰着我。 I have a list which is created by user input, and I want to find the longest word from the list. 我有一个由用户输入创建的列表,我想从列表中找到最长的单词。 I have been able to get the list but my output is incorrect and I am having an issue trying to compare the words from the list. 我已经能够获取列表,但是我的输出不正确,并且在尝试比较列表中的单词时遇到问题。 I realize this is a duplicate question in a couple of other threads but after trying those suggestions I am still having an issue. 我意识到这在其他几个线程中是一个重复的问题,但是在尝试了这些建议之后,我仍然遇到问题。 This is what I have thus far, and thank you in advance: 这是我到目前为止的内容,在此先感谢您:
def find_longest_word(wordList):
longest=''
previous=''
for word in wordList:
if len(word)>len(longest):
longest=word
print(longest)
else:
previous=word
print(previous)
print('Please enter a few words and I will find the longest word:','\n')
words = input()
print('\n')
wordList = words.split()
print('The list of words entered is:','\n')
print(wordList)
find_longest_word(wordList)
Have you tried the following? 您是否尝试过以下方法?
def find_longest_word(wordList):
return max(wordList, key=len)
This simple line finds the maximum value of the wordList, comparing the values in the list by their length. 这行简单的代码找到了wordList的最大值,将列表中的值按其长度进行比较。
Let's define a list of words as such: 让我们这样定义一个单词列表:
wordList = ['word', 'longestWord', 'shorter']
You can find the index of the longest word with 您可以找到最长的单词的索引
maxIndex = max(enumerate(map(lambda x: len(x), wordList)), key=(lambda x: x[1]))
and finally see the longest word with: 最后看到最长的单词:
wordList[maxIndex[0]]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.