Kashif
Kashif

Reputation: 3327

applying list of functions to list of arguments in python

I have the following lists

fncs = ["MyLinkedList","addAtHead","get","addAtTail"]
args = [[],[8],[1],[81]]

And I want to return

[MyLinkedList(), addAtHead(8), get(1), addAtTail(81)]

I thought I could use fnc_vals = [f(x) for f, x in zip(fncs, args)] but that doesn't seem to work since my fncs list is a list of strings. How can I apply a list of functions to a list of arguments (in Python)?

Upvotes: 1

Views: 64

Answers (2)

brunns
brunns

Reputation: 2764

If the functions are in the local namespace, just remove the quotes:

fncs = [MyLinkedList, addAtHead, get, addAtTail]
args = [[], [8], [1], [81]]

If the 1st list must be strings, you can get the function objects with:

function_names = ["MyLinkedList", "addAtHead", "get", "addAtTail"]
functions = [locals()[fn] for fn in function_names]

If, that is, the functions are named in the local namespace.

Upvotes: 1

Netwave
Netwave

Reputation: 42678

If you have a list of strings refering to the current scope functions you can use globals or locals:

fnc_vals = [golbals()[f](x) for f, x in zip(fncs, args)]

Check this example:

>>> def foo(x):
...     return x
... 
>>> globals()["foo"](10)
10

You can also build your own functions addressing dictionary:

>>> def foo(x):
...     return x
... 
>>> def bar(x):
...     return x + 10
... 
>>> func_dict = {f.__name__:f for f in (foo, bar)}
>>> func_dict["foo"](10)
10

Upvotes: 1

Related Questions