python - Python中的函数语句返回列表列表中某些列表的总和

标签 python python-3.x functional-programming

我正在尝试返回父列表中包含的所有长度 > 1 的子列表中包含的元素总数:

x = [[4], [6, 4, 9], [4, 6], [0], []]

# 1) Filter on x for only lists whose length is > 1
# 2) Reduce the new list to a sum of the lengths of each sublist
# result should be 5

这是我试过的:

# Invalid as y is a list
reduce((lambda x, y: len(x) + y), filter((lambda x: len(x) > 1), x))

我认为 map 可能以某种方式涉及,但我不确定如何构造它。

最佳答案

如果您想要一种函数式方法,filter summap 可以完成这项工作:

In [10]: x = [[4], [6, 4, 9], [4, 6], [0], []]

In [11]: sum(map(len, filter(lambda s: len(s) > 1, x)))
Out[11]: 5

关于python - Python中的函数语句返回列表列表中某些列表的总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35707224/

相关文章:

python-3.x - 有没有办法为Windows安装cython-bbox?

javascript - Ramda.js:要列出的参数

python - 默认为并选择 Tkinter 列表框中的第一项

python - 类 foo 、类 foo() 和类 foo(object) 之间的区别?

python - scrapy项目中errback和callback中各种异常如何处理?

python - 属性错误: module 'math' has no attribute '_name_'

functional-programming - 函数式编程: Declarative vs imperative

oop - 闭包:为什么它们如此有用?

python - Django 得到了一个意外的关键字参数 'id'

python - Websockify 错误 - 地址已在使用中