简体   繁体   中英

get average length of words using python reduce

I am attempting to get the average length of words in a file using reduce, but I am getting the following error "TypeError: object of type 'int' has no len()" which i find baffling because the file is filled with words and I am simply getting the length of each

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

The reduce function will work upon two elements of the list at a time and then work with the returned value along with the next element. So the reduce function is used in a wrong way. Quoting from the docs

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) .

(emphasis mine)

Using sum along with map is a better way ( as mentioned )

That is

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

This would give you the average as expected

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM