Bri*_*HVB 4 python functional-programming python-3.x
我正在尝试返回父列表中包含长度> 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
Run Code Online (Sandbox Code Playgroud)
这是我尝试过的:
# Invalid as y is a list
reduce((lambda x, y: len(x) + y), filter((lambda x: len(x) > 1), x))
Run Code Online (Sandbox Code Playgroud)
我认为地图可能会以某种方式涉及,但我不确定如何构建它.
如果你想要一个功能性的方法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
Run Code Online (Sandbox Code Playgroud)
为什么你就是不使用生成器表达式中sum()?
>>> x = [[4], [6, 4, 9], [4, 6], [0], []]
>>>
>>> sum(len(i) for i in x if len(i)>1)
5
Run Code Online (Sandbox Code Playgroud)
阅读这篇文章,关于reduce()Guido van van Rossum在Python 3000中的命运.http://www.artima.com/weblogs/viewpost.jsp?thread=98196
如果你是一个符合逻辑的做法寻找一个功能,您就可以只使用map()和sum()和仍然没有reduce()和filter():-)
>>> x = [[4], [6, 4, 9], [4, 6], [0], []]
>>>
>>> sum(map(lambda i:bool(i and i.pop(0) and i)+len(i), x))
5
Run Code Online (Sandbox Code Playgroud)