如何在python中找到最长的单词?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32833575/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 12:21:34  来源:igfitidea点击:

how to find the longest word in python?

python

提问by python paradise

I a new to python and am stuck on this one exercise. I am supposed to enter a sentence and find the longest word. If there are two or more words that have the same longest length, then it is to return the first word. This is what I have so far:

我是 python 的新手,并且坚持这个练习。我应该输入一个句子并找到最长的单词。如果有两个或多个单词的最长长度相同,则返回第一个单词。这是我到目前为止:

def find_longest_word(word_list):  
    longest_word = ''  
    for word in word_list:    
          print(word, len(word))  


words = input('Please enter a few words')  
word_list = words.split()  
find_longest_word(word_list)  

But I do not know how to compare the lists and return the first/longest word.

但我不知道如何比较列表并返回第一个/最长的单词。

采纳答案by Froziph

You shouldn't print out the length of each word. Instead, compare the length of the current wordand the length of longest_word. If wordis longer, you update longest_wordto word. When you have been through all words, the longest world will be stored in longest_word.

你不应该打印出每个单词的长度。相反,比较当前word的长度和 的长度longest_word。如果word更长,则更新longest_wordword. 当你遍历完所有单词后,最长的世界将存储在longest_word.

Then you can print or return it.

然后您可以打印或返回它。

def find_longest_word(word_list):
    longest_word = ''
    for word in word_list:
        if len(word) > len(longest_word)
            longest_word = word
    print longest_word

edit: levi's answer is much more elegant, this is a solution with a simple for loop, and is somewhat close to the one you tried to make yourself.

编辑:levi 的回答要优雅得多,这是一个带有简单 for 循环的解决方案,并且与您尝试自己制作的解决方案有些接近。

回答by levi

Use maxpython built-in function, using as keyparameter the lenfunction. It would iterate over word_listapplying lenfunction and then returning the longest one.

使用maxpython内置函数,keylen函数用作参数。它会迭代word_list应用len函数,然后返回最长的函数。

def find_longest_word(word_list):  
    longest_word =  max(word_list, key=len)
    return longest_word

回答by Fredaugermorin

Compare each word to the longest one yet, starting with the length of 0. If the word is longer than the longest yet, update the word and the longest_size. Should look similar to this:

将每个单词与最长的单词进行比较,从长度 0 开始。如果单词比最长的单词长,则更新单词和longest_size。应该类似于:

def find_longest_word(word_list):  
    longest_word = ''  
    longest_size = 0   
for word in word_list:    
    if len(word) > longest_size
        longest_word = word
        longest_size = len(word)      
return longest_word

words = input('Please enter a few words')  
word_list = words.split()  
find_longest_word(word_list)