Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Zip and apply a list of functions over a list of values in Python

Tags:

python

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.

like image 977
Paul Smith Avatar asked Nov 20 '10 05:11

Paul Smith


People also ask

How do I apply a list of functions in Python?

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.

What does zip (* list do in Python?

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.

Why do you use the zip () method in Python?

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.


2 Answers

[x(y) for x, y in zip(functions, values)]
like image 180
Ignacio Vazquez-Abrams Avatar answered Oct 12 '22 16:10

Ignacio Vazquez-Abrams


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)
like image 41
Ben Jackson Avatar answered Oct 12 '22 17:10

Ben Jackson