Skip to main content
 首页 » 编程设计

python之试图让程序给我一个句子中最长的单词

2025年05月04日11kenshinobiy

问题是,当我有一个句子包含两个字母数量相同的单词时,我如何让程序在阅读时给我第一个最长的单词而不是两个?

import sys  
 
inputsentence = input("Enter a sentence and I will find the longest word: ").split() 
longestwords = [] 
for word in inputsentence: 
    if len(word) == len(max(inputsentence, key=len)): 
        longestwords.append(word) 
 
print ("the longest word in the sentence is:",longestwords) 

示例:快速的棕色狐狸...现在程序给了我“快速”和“棕色”,如何调整我的代码以只给我“快速”,因为它是第一个最长的单词?

请您参考如下方法:

我会完全摆脱 for 循环,只需这样做:

>>> mystr = input("Enter a sentence and I will find the longest word: ") 
Enter a sentence and I will find the longest word: The quick brown fox 
>>> longest = max(mystr.split(), key=len) 
>>> print("the longest word in the sentence is:", longest) 
the longest word in the sentence is: quick 
>>>