Functional operator in Python to return the sum of specific lists to a list of lists

I am trying to return a counter of the total number of elements contained in all sublists with a length> 1 contained in the parent list:

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

Here is what I tried:

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

I think the map may be involved in some way, but I'm not sure how to structure it.

+4
source share
6 answers

If you need a functional approach filter sumand mapcomplete the task:

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
+6
source

Why don't you just use the expression in sum()?

>>> x = [[4], [6, 4, 9], [4, 6], [0], []]
>>> 
>>> sum(len(i) for i in x if len(i)>1)
5

reduce() Python 3000 Guido van van Rossum. 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
+5

, , .

.

sum(len(y) for y in x if len(y) > 1)
+4

, , , . , -

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
+3

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
+2

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
+2

All Articles