Reputation: 7060
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?
Upvotes: 0
Views: 2831
Reputation: 532053
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 1
s from a filtered iterable.
sum(1 for x in l if x.contains("f"))
Upvotes: 2