使用python reduce获得单词的平均长度

时间:2015-04-02 13:25:21

标签: python

我试图使用reduce来获取文件中单词的平均长度,但是我收到以下错误" TypeError:类型' int'没有len()"我发现令人困惑,因为文件充满了单词,我只是得到每个

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

1 个答案:

答案 0 :(得分:2)

reduce函数一次对列表的两个元素起作用,然后使用返回的值和下一个元素。因此reduce函数以错误的方式使用。引用文档

  

将两个参数累积的函数从左到右应用于iterable的项目,以便将iterable减少为单个值。例如,reduce(lambda x, y: x+y, [1, 2, 3, 4, 5])计算((((1+2)+3)+4)+5)

(强调我的)

使用summap是更好的方式(as mentioned

那是

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

这将为您提供预期的平均值