python-3.x - 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()
有人可以指出我哪里出错了。
解决方案
为了完整起见,我还想展示map
一种更实用的方法:
total_length = sum(map(len, names))
推荐阅读
- c# - C#中如何给多个控件添加函数和属性
- node.js - 从其他工作表上创建一个新工作表并复制他的样式(nodejs,googleSheets)
- angular - 离子硬件后退按钮执行两次
- php - PHP cURL 响应问题
- perl - 有没有办法在 Perl 中生成带有自定义徽标的二维码?
- gentics-mesh - 我在哪里可以在 Gentics Mesh 中切换到 TrackingSearchProvider 而不是 ElasticSearchProvider
- javascript - 如何在javascript对象中动态插入?
- flutter - Moor 限制 SELECT 但不是 JOINS
- php - C 函数 pow() 不会在共享主机服务器中执行
- javascript - Netlify cms 更改 github 名称