我正在尝试返回父列表中包含的所有长度 > 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
sum
和 map
可以完成这项工作:
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/