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 :)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With