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

2024-09-24 22:31:15 发布

您现在位置: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)

例子:快速棕色狐狸…现在程序给我“快速”和“棕色”,如何调整我的代码,使我只给“快”从第一个最长的单词?在


Tags: theinimport程序lenlongestsys字母
3条回答

只需打印列表中的第一个:

print ("the longest word in the sentence is:",longestwords[0])

可能有更好的方法来实现这一点,但这需要对代码进行最少的修改。在

为什么不只是:

longest_word = None

for word in inputsentence:
    if len(word) == len(max(inputsentence, key=len)):
        longest_word = word

print ("the longest word in the sentence is:",longest_word)

我会完全摆脱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
>>>

相关问题 更多 >