Reputation: 2944
I'd like to execute some code for every element in a list that match some property. So my code would look like:
for x in filter(f, lx):
do some stuff
But my function f is defined in the object x, so I have to write:
for x in filter(lambda x: x.f(), lx):
do some stuff
Maybe I'm a bit picky, but I find it stupid to define a lambda function when I already define this function somewhere else... Is there a more efficient and concise way to do what I want ?
Upvotes: 0
Views: 82
Reputation: 37606
Use directly the f
method defined in your class:
for x in filter(X.f, lx):
# do some stuff
A more efficient way using the itertools
module to avoid the creation of a new list and use beautiful python generator:
import itertools
for x in itertools.ifilter(X.f, lx):
# do some stuff
Assumning X
is the class of element in lx.
Small example:
class A:
def __init__ (self, b):
self.b
def check (self):
return self.b < 10
l = [A(8), A(40), A(5), A(7), A(33)]
for a in filter(A.check, l):
print a.b
Upvotes: 3
Reputation: 375504
Perhaps avoid filter:
for x in lx:
if x.f():
# do some stuff
It's more lines, but clearer code. If you find yourself doing it often, make a generator:
def filter_f(lx):
for x in lx:
if x.f():
yield x
...
for x in filter_f(lx):
# do something
(this came out longer than you'd like I suspect, but demonstrates another way to do it.)
Upvotes: 1