2014-11-23 54 views
3

需要查找字符串中最長的單詞並打印該單詞。 1.)要求用戶輸入以空格分隔的句子。 2.)查找並打印最長的單詞。如果兩個或兩個以上的單詞的長度相同,則會打印第一個單詞。比較字符串中單詞的長度

這是我迄今爲止

def maxword(splitlist):  #sorry, still trying to understand loops 
    for word in splitlist: 
     length = len(word) 
     if ?????? 

wordlist = input("Enter a sentence: ") 
splitlist = wordlist.split() 

maxword(splitlist) 

試圖字的lenghts比較在森泰斯當我擊中牆壁。我是一名使用python 5周的學生。

回答

2
def longestWord(sentence): 
    longest = 0 # Keep track of the longest length 
    word = ''  # And the word that corresponds to that length 
    for i in sentence.split(): 
     if len(i) > longest: 
      word = i 
      longest = len(i) 
    return word 

>>> s = 'this is a test sentence with some words' 
>>> longestWord(s) 
'sentence' 
0
sentence = raw_input("Enter sentence: ") 
words = sentence.split(" ") 
maxlen = 0 
longest_word = '' 
for word in words: 
    if len(word) > maxlen: 
      maxlen = len(word) 
      longest_word = word 
print(word, maxlen) 
1

你會在正確的方向。你的代碼大部分看起來不錯,你只需要完成邏輯來確定哪個是最長的單詞。由於這似乎是一個家庭作業問題,我不想給你直接的答案(儘管其他人對我這樣的學生沒有任何用處),但有多種方法可以解決這個問題。

你正確地得到每個單詞的長度,但是你需要什麼來比較每個長度對?試着大聲說出問題,以及你如何親自解決問題。我認爲你會發現你的英文描述很好地翻譯成一個Python版本。

另一種不使用if語句的解決方案可能使用內置的python函數max,該函數接受一列數字並返回它們的最大值。你怎麼能用它?

+0

謝謝你的回答。這正是我陷入困境的地方。我知道我想做什麼,我只是不知道如何實現它。尋求幫助是我的最後手段。 – Mixtli 2014-11-23 20:53:27

1

可以使用max用鑰匙:

def max_word(splitlist):  
    return max(splitlist.split(),key=len) if splitlist.strip() else "" # python 2 


def max_word(splitlist): 
    return max(splitlist.split()," ",key=len) # python 3 

或者使用try /除建議由喬恩·克萊門茨:

def max_word(splitlist): 
    try: 
     return max(splitlist.split(),key=len) 
    except ValueError: 
     return " " 
+0

Python 3.4有一個['default'關鍵字參數](https://docs.python.org/3.4/library/functions.html#max),當iterable爲空時返回。 – 2014-11-23 20:23:01

+0

@kroolik真的,沒有看到python3標記 – 2014-11-23 20:27:50

+0

感謝澄清他們兩個 – Mixtli 2014-11-23 20:30:49

1

您可以使用nlargest從heapq模塊

import heapq 
heapq.nlargest(1, sentence.split(), key=len) 
+0

非常好....... – pad 2014-11-23 21:33:08