2015-04-02 62 views
1

我試圖獲得文件中使用減少的單詞的平均長度,但我得到以下錯誤「TypeError:類型'int'的對象有沒有len()」哪我覺得莫名其妙,因爲該文件充滿了的話,我僅僅讓每個獲得使用python的單詞的平均長度減少

def averageWord(): 
    myWords = open('myfile.txt', 'r').read().split(' ') 
    avg = (reduce(lambda x,y: len(x) + len(y) ,myWords))/len(myWords) 
    print avg 
+4

使用'sum()'與ge nerator表達式不是'reduce'。使用'reduce'會導致不必要的複雜:'reduce(lambda x,y:x + len(y),myWords,0)'。 – 2015-04-02 13:26:43

+0

爲什麼只有第二個參數調用len,爲什麼最後一個參數是0? – godzilla 2015-04-02 13:50:59

回答

2

長度reduce功能將在同一時間在列表中的兩個元素的工作,然後用與沿返回值工作下一個元素。所以reduce函數以錯誤的方式使用。從文檔

Apply function of two arguments cumulatively to the items of iterable, from left to right, so as to reduce the iterable to a single value. For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates ((((1+2)+3)+4)+5) .

(重點煤礦)

map一起使用sum報價是

avg = sum(map(len,myWords)) /len(myWords) 

這會給你平均一個更好的方法(as mentioned

如預期的那樣

+0

如果使用正確,那麼'reduce'就沒有錯。 – 2015-04-02 13:37:09

+0

@AshwiniChaudhary是的。但OP在這裏錯誤地使用了它! :)就像你上面提到的那樣,這是一個相當複雜的過程!我只是試圖向OP解釋這一點! – 2015-04-02 13:38:36