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

时间:2013-11-26 21:17:09

标签: 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)

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

4 个答案:

答案 0 :(得分:8)

我会完全摆脱for-loop而只是这样做:

>>> 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
>>>

答案 1 :(得分:1)

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

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

可能有更好的方法可以做到这一点,但这需要对代码进行最少的修改。

答案 2 :(得分: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)

答案 3 :(得分:0)

更多pythonic方式

import sys 

inputsentence = input("Enter a sentence and I will find the longest word: ").split()
# use function len() as criteria to sort
inputsentence.sort(key=len)
# -1 is last item on list
print ("the longest word in the sentence is:", sentence[-1])