首页 > 解决方案 > Python reduce 函数无法按预期方式工作

问题描述

我有一个非常简单的用例,其中我有一个名称列表,我必须计算名称列表中所有单词的总长度。下面是我的代码库,但它不能按我期望的方式工作:

In [13]: names = ['John', 'Arya', 'Maya', 'Mary']                                                                                                                             

In [14]: from functools import reduce                                                                                                                                         

In [15]: check = reduce(lambda x, y: len(x) + len(y), names)                                                                                                                  
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-15-39802d43150a> in <module>
----> 1 check = reduce(lambda x, y: len(x) + len(y), names)

<ipython-input-15-39802d43150a> in <lambda>(x, y)
----> 1 check = reduce(lambda x, y: len(x) + len(y), names)

TypeError: object of type 'int' has no len()

有人可以指出我哪里出错了。

标签: python-3.x

解决方案


为了完整起见,我还想展示map一种更实用的方法:

total_length = sum(map(len, names))

推荐阅读