2016-05-15 96 views
2
def word(longest): 
    max_length = 0; 
    words = longest.split(" ") 
    for x in words: 
     if len(words[x]) > max_length: 
     max_length = len(words[x]) 

    return max_length 

word("Hello world") 

確切的錯誤:爲什麼我在python中得到這個代碼的類型錯誤?

TypeError: list indices must be integers, not str 

林仍然是一個在這個所以請,沒有意思的意見小白。

+2

x是的話,在你的名單的話不是字的位置 – Keatinge

回答

3

因爲您使用x作爲索引,所以它實際上是字符串本身。

你可以這樣做:

for x in words: 
     if len(x) > max_length: 
     max_length = len(x) 
3

當你這樣做for x in wordsx就是一個字。所以你不需要words[x]來得到這個詞。 words[x]預計x是一個整數,但它是一個字符串,這就是爲什麼你會得到這個錯誤。

所以,你應該寫:

for x in words: 
    if len(x) > max_length: 
     max_length = len(x) 
相關問題