Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

map with function for each element?

Very often I process single elements of tuples like this:

size, duration, name = some_external_function()
size = int(size)
duration = float(duration)
name = name.strip().lower()

If some_external_function would return some equally typed tuple I could use map in order to have a (more functional) closed expression:

size, duration, name = map(magic, some_external_function())

Is there something like an element wise map? Something I could run like this:

size, duration, name = map2((int, float, strip), some_external_function())

Update: I know I can use comprehension together with zip, e.g.

size, duration, name = [f(v) for f, v in zip(
   (int, float, str.strip), some_external_function())]

-- I'm looking for a 'pythonic' (best: built-in) solution!

To the Python developers:

What about

(size)int, (duration)float, (name)str.strip = some_external_function()

? If I see this in any upcoming Python version, I'll send you a beer :)

like image 636
frans Avatar asked Dec 10 '22 00:12

frans


1 Answers

Quite simply: use a function and args unpacking...

def transform(size, duration, name):
    return int(size), float(duration), name.strip().lower()

# if you don't know what the `*` does then follow the link above...    
size, name, duration = transform(*some_external_function())

Dead simple, perfectly readable and testable.

like image 85
bruno desthuilliers Avatar answered Dec 18 '22 14:12

bruno desthuilliers