我正在尝试使用reduce获取文件中单词的平均长度,但出现以下错误“TypeError: object of type 'int' has no len()”,这让我感到困惑,因为文件已满用文字,我只是得到每个文字的长度
def averageWord():
myWords = open('myfile.txt', 'r').read().split(' ')
avg = (reduce(lambda x,y: len(x) + len(y) ,myWords)) / len(myWords)
print avg
最佳答案
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)
.
(强调我的)
使用sum
以及map
是一个更好的方法( as mentioned )
那就是
avg = sum(map(len,myWords)) /len(myWords)
这将为您提供预期的平均值
关于python - 使用 python reduce 获取单词的平均长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29414131/