AirTycoon
AirTycoon

Reputation: 395

python - map muliple functions (in a iterable), single object

I am fairly new to python and yet to fully understand its concepts. Orginally the code was something like this

def isSomething(s):
    result=False
    for f in listFunctions:
        if f(s):
            result=True
return result

So I was wondering if there is anything like this

def isSomething(s):
   return any(mapManyFunctions2Object(listFunctions,s))

where mapManyFunctions2Object() is just like but maps iterable list of Functions and a object.

Is there any standard function that could replace mapManyFunctions2Object() ?

Upvotes: 0

Views: 126

Answers (3)

unutbu
unutbu

Reputation: 879421

You could use any with a generator expression:

def isSomething(s):
   return any(f(s) for f in listFunctions))

One nice thing about using any with a generator expression is that any will short-circuit as soon as some f(s) returns a Truish value. So not all the functions in listFunctions will be called unless they all happen to return Falsish values.

Upvotes: 3

roman
roman

Reputation: 117350

you can do this easily:

>>> listFunctions = [lambda x: x == 1, lambda x: x == 2, lambda x: x == 3]
>>> def isSomething(x):
...     return any(f(x) for f in listFunctions)
... 
>>> isSomething(3)   # run functions from list on 3, get results False, False and, finally, True
True
>>> isSomething(5)   # run functions from list on 5, all results is False
False

Upvotes: 0

abarnert
abarnert

Reputation: 365707

You can write such a function trivially:

def apply_all(functions, arg):
    return [function(arg) for function in functions]

Or, if you want a 3.x-style map-like:

def apply_all(functions, arg):
    yield from (function(arg) for function in functions)

However, you really don't need to, given that you can just use the expression itself just as easily.

map is worth having for historical reasons, familiarity from other languages, etc.—so long as the thing to be mapped is a nicely-named function, many people will instantly understand what map(frotz, widgets) means. I don't think that'll be true for apply_all(frotzers, widget).


Just for fun, to define apply_all in terms of map:

def apply_all(functions, arg):
    return map(lambda function: function(arg), functions)

Upvotes: 1

Related Questions