Python中的函数语句,用于返回列表列表中某些列表的总和
我试图返回父列表中长度>1的所有子列表中包含的元素总数:Python中的函数语句,用于返回列表列表中某些列表的总和,python,python-3.x,functional-programming,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 reduc
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))
我想可能会涉及到地图,但我不确定如何组织它。你有一个良好的开端,但你使它比需要的复杂得多 你可以把一个生成器求和
sum(len(y) for y in x if len(y) > 1)
为什么不在sum()中使用
阅读这篇由Guido van Rossum撰写的关于Python 3000中reduce()
命运的文章
如果您正在寻找一种功能方法作为逻辑方法,您可以只使用map()
和sum()
,而不使用reduce()
和filter()
:-)
我同意其他答案,即您的尝试很复杂,您的问题可能有简单的解决方案,但我想指导您的尝试。你很接近,在你的尝试中有一点改变-
x = [[4], [6, 4, 9], [4, 6], [0], []]
reduce(lambda x,y: (len(x) + len(y)) if isinstance(x, list) else (x + len(y)), filter((lambda x: len(x) > 1), x))
# result would be 5
您还提到了一种map
方法。这是一个有效的
x = [[4], [6, 4, 9], [4, 6], [0], []]
In [2]: sum(map(lambda x: len(x) if len(x) > 1 else 0, x))
Out[2]: 5
如果您需要一种功能性方法,则过滤器
求和
和映射
将完成以下工作:
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
对生成器表达式使用sum
不是我所说的函数式
>>> from functools import reduce
>>> from operator import add
>>> x = [[4], [6, 4, 9], [4, 6], [0], []]
>>> reduce(add, filter(1 .__lt__, map(len, x)))
5
啊,我不知道可以这样加一个if条款。我用它来表示返回'this'if(something)other'that'
,但不知道它可以在其他上下文中工作。Thanks@BrianHVB是的。在任何类型的生成器/理解中都可以这样做,所以我得到了len(x)在lambda中所指的,但我认为第二个值是累加器。结果是正确的,但是len(y)在lambda中做了什么?对于Python 3,需要从functools导入reduce
。@BrianHVB明白了你的意思,我修改了我的答案,但我建议这个解决方案只是为了帮助你的尝试,我们已经看到了其他简单的解决方案。过滤器(lambda s:len(s)>1,x)
可以是过滤器(None,x)
,因为我们知道OP的列表只包含列表。@gill,这将删除空列表,而不是包含1个或更少元素的列表。
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
>>> from functools import reduce
>>> from operator import add
>>> x = [[4], [6, 4, 9], [4, 6], [0], []]
>>> reduce(add, filter(1 .__lt__, map(len, x)))
5