2013-11-26 49 views
1

問題是,當我有一個句子包含兩個具有相同字母數量的單詞時,如何讓該程序在閱讀時給我第一個最長的單詞而不是兩者?試圖讓程序給我一個句子中最長的單詞

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) 

例如:敏捷的棕色狐狸......現在的計劃給了我「快」和「棕色」,如何調整我的代碼,只要給我「快」,因爲它的第一個最長的單詞?

+1

嘗試用突破經過最長的詞.append(單詞)行 – llazzaro

回答

1

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

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

有可能更好的方法來做到這一點,但是這需要至少修改你的代碼。

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

更Python的方式

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]) 
相關問題