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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With