Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Functional statement in Python to return the sum of certain lists in a list of lists

I'm trying to return the count of the total number of elements contained in all sublists with a length > 1 contained in a 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

This is what I have tried:

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

I think a map might be involved somehow, but I'm not sure how to structure it.

like image 832
BrianHVB Avatar asked Nov 28 '22 23:11

BrianHVB


1 Answers

If you wanted a functional approach filter sum and map would do the job:

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
like image 94
Padraic Cunningham Avatar answered Dec 05 '22 03:12

Padraic Cunningham