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

1 python

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

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)
Run Code Online (Sandbox Code Playgroud)

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

iCo*_*dez 8

我会完全摆脱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
>>>
Run Code Online (Sandbox Code Playgroud)