0

I want to use python in a more declarative way, using predicates as much as possible to simplify things, but I'm having trouble seeing how to do that "simply" in python.

For example, when counting items in a list I want to be able to pass in a predicate, like this:

mylist.count(lambda x: x.contains("f"))

to count items in the list that contain and "f".

I can see how to do this with itertools:

sum(map(lambda x: 1 if x.contains("f") else 0, l))

but that's worse than a for loop. Am I missing something or does Python just not allow for this kind of expression?

1
  • 2
    sum(x.contains("f") for x in l); bool is a subclass of int, and a sequence of bool values can be summed directly. Commented Jul 22, 2020 at 20:19

1 Answer 1

2

The "simplest" (or at least, most decomposable) way would use operator.methodcaller along with sum.

from operator import methodcaller

p = methodcaller("contains", "f")
sum(map(p, l))

This works because contains returns an instance of bool, which is a subclass of int.

You can also use a generator expression to create a sequence of 1s from a filtered iterable.

sum(1 for x in l if x.contains("f"))
Sign up to request clarification or add additional context in comments.

2 Comments

Or sum(x.contains("f") for x in l)
Ugh, how did I forget to include that i my answer?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.