0

I have a simple example as so:

import numpy as np
func_dict1 = {0: np.sin, 1: np.cos, 2: np.tan}
out = map(func_dict1.get, np.array([0, 2, 0]))

Here I am picking out three functions by their dictionary keys. Now I want to pass unique arguments to each function like so:

[f(x) for f,x in zip(out, [3,1,2])]

which renders the output:

[0.1411200080598672, 1.557407724654902, 0.9092974268256817]

But how can I do this with map?

I thought this would work, but it does not:

map(out, [3,1,2])

Where am I going wrong? And is there any benefit to using map over list comprehension? My prior is that it is faster but I confess to not being an expert on the subject.

2 Answers 2

3

map is designed to take a single function and apply it to every item in an iterable. You are applying a different function to different items. I think the list comprehension is an elegant way of doing it.

Sign up to request clarification or add additional context in comments.

Comments

1

WARNING: you probably don't want to use map and this answer might confuse you more than it helps ;).

However, as you asked how you can make map do this and as it's python, let's take the challenge: one way to achieve what you want is by wrapping your out in an object that is callable (so behaves like a function) and on each call also advances to the next function. For example like this:

# yours
import numpy as np
func_dict1 = {0: np.sin, 1: np.cos, 2: np.tan}
out = map(func_dict1.get, np.array([0, 2, 0]))

# extend like this
class FuncIterCaller:
    def __init__(self, funcs):
        self.funcs = funcs

    def __call__(self, *args, **kwds):
        return next(self.funcs)(*args, **kwds)

res = map(FuncIterCaller(out), [3,1,2])

# to see what's inside:
print(list(res))

Comments

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.