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

标签 python

我正在尝试使用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/

相关文章:

python - 无法导入 pymongo ubuntu

python - CSVkit 到底在哪里?

python - 如何获取类的所有实例

python - FutureWarning : elementwise comparison failed; returning scalar, 但将来会执行元素比较

python - conda-build 错误地提示 meta.yaml 中不包含依赖项

python - 使用 selenium python 网络驱动程序从 Angular 单击表格中的所有行

python - 为什么这个正则表达式不起作用?

python - 使用Python脚本在记事本中进行算术运算

python - 我如何使用 pony.vim

python - 在 Pandas 中使用多索引数据帧进行高级平均