2016-03-09 31 views
-2
def find_longest_word(string): 
    d = [] 
    a = string.split() 
    for x in a: 
     b = (x.count("") - 1) 
     d.append(b) 
     f = max(d) 
     print (x, f) 

find_longest_word("hello my name is k") 

該程序將打印每個單詞的長度最長旁邊每個,但我只希望它打印最長的單詞。請幫忙。如何讓程序只顯示最長的單詞而不是每個字符串中的單詞?

+1

使用'len'獲得Python中的字符串的長度,如果你不希望它打印了一堆的話,就把'print'外循環。 – jpmc26

回答

1

試試這個:

def find_longest_word(string): 
    a = string.split() 
    f = -1 
    longest = None 
    for x in a: 
     if len(x) > f: 
      f = len(x) 
      longest = x 
    print (longest, f) 

>>> find_longest_word("hello my name is k") 
('hello', 5) 
+0

謝謝!這工作完美 – Kth

0

x.count("")返回的次數""顯示出的字符串中。假設字符串是「mystring」。 "m"不是"","y"不是"","s"不是""等。總數:0.要獲取字符串的長度,請使用len(x)。此外,您使f等於d中的最大數字,而不是b。下面是修改後的版本:

def find_longest_word(string): 
    a = string.split() 
    longest = max(((word, len(word)) for word in a), key=lambda x: x[1]) 
    print longest 

測試:

find_longest_word("This is my sentence that has a longest word.") 

輸出:

('sentence', 8) 

如果你想讓它打印出來像sentence: 8,使用print '{}: {}'.format(longest)

1

這裏有一個短和簡單的功能找到一個句子中最長的單詞:

def find_longest_word(s): 
    return max([(len(w), w) for w in s.split(" ")])[1] 

實施例:

find_longest_word("This is an incredibly long sentence!") 
>>> incredibly 

說明: 這將創建列表解析和元組的s.split(" ")的列表,並然後存儲單詞和在元組中的字本身的長度。然後在元組列表上調用max函數,並且它檢索具有最長字長度的元組(即,第零元組參數),然後它簡單地將該字(即,第一元組參數)與...)[1]

注意:如果要返回單詞的長度和單詞本身,可以簡單地將該函數修改爲:return max([(len(w), w) for w in s.split(" ")])。這將刪除對元組的索引並返回完整的元組。

1

一個一個班輪:

def longest(s): 
    return sorted(s.split(), key=len, reverse=True)[0] 

print longest("this is a string") 
相關問題