Is there idiomatic and/or elegant Python for zipping and applying a list of functions over a list of values?
For example, suppose you have a list of functions:
functions = [int, unicode, float, lambda x: '~' + x + '~']
and a list of values:
values = ['33', '\xc3\xa4', '3.14', 'flange']
Is there a way to apply the ith function to the ith value and return a list of the same length of the transformed values, while avoiding this ugly list comprehension?
[functions[i](values[i]) for i in range(len(functions))] # <- ugly
What I want is something like zip()
+ map()
(zipmap()
!) the functions list with the values list and have the functions be applied to their paired values. I thought itertools
might offer something relevant, but functions like imap
and starmap
are for mapping a single function over an iterable, not an iterable of functions over another iterable.
Use the map() Function to Apply a Function to a List in Python. The map() function is used to apply a function to all elements of a specific iterable object like a list, tuple, and more. It returns a map type object which can be converted to a list afterward using the list() function.
Python's zip() function is defined as zip(*iterables) . The function takes in iterables as arguments and returns an iterator. This iterator generates a series of tuples containing elements from each iterable. zip() can accept any type of iterable, such as files, lists, tuples, dictionaries, sets, and so on.
Python zip() method takes iterable or containers and returns a single iterator object, having mapped values from all the containers. It is used to map the similar index of multiple containers so that they can be used just using a single entity.
[x(y) for x, y in zip(functions, values)]
These solutions seem overly complicated: map
already zips its arguments:
map(lambda x,y:x(y), functions, values)
Or, if you prefer the iterator version:
from itertools import imap
imap(lambda x,y:x(y), functions, values)
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