DenisKolodin
DenisKolodin

Reputation: 15131

How to map a list of data to a list of functions?

I have the following Python code:

data  = ['1', '4.6', 'txt']
funcs = [int, float, str]

How to call every function with data in corresponding index as an argument to the function? Now I'm using the code:

result = []
for i, func in enumerate(funcs):
    result.append(func(data[i]))

map(funcs, data) don't work with lists of functions ( Is there builtin function to do that simpler?

Upvotes: 3

Views: 2975

Answers (5)

martineau
martineau

Reputation: 123541

map() will work with sequences of functions, although perhaps not in the way you thought:

data  = ['1', '4.6', 'txt']
funcs = [int, float, str]

result = list(map(lambda f,d: f(d), funcs, data))
# or
result = list(map(lambda d,f: f(d), data, funcs))

Upvotes: 3

Tony Veijalainen
Tony Veijalainen

Reputation: 5565

If you need the values one by one, you can also create generator for values:

def my_funcvals(funcs,vals):
    return ("%s(%r) = %r" %(f.__name__,d, f(d)) for d,f in zip(data, funcs))

data  = ['1', '4.6', 'txt']
funcs = [int, float, str]

for result in my_funcvals(funcs, data):
    print result

Upvotes: 0

kennytm
kennytm

Reputation: 523734

You could use zip* to combine many sequences together:

zip([a,b,c,...], [x,y,z,...]) == [(a,x), (b,y), (c,z), ...]

then you could iterate on this new sequence and make each function apply on the corresponding data. Since you just want to collect them into a list, list comprehension is much better than a for-loop:

result = [f(x) for f, x in zip(funcs, data)]

Note: * Use itertools.izip if you are using Python 2.x and the lists are very long.)

Upvotes: 9

pyfunc
pyfunc

Reputation: 66739

>>> data  = ['1', '4.6', 'txt']
>>> funcs = [int, float, str]
>>> result = [funcs[pos](x) for pos, x in enumerate(data)]
>>> result
[1, 4.5999999999999996, 'txt']
>>> 

Upvotes: 2

Knio
Knio

Reputation: 7120

[f(d) for d,f in zip(data, funcs)]

Upvotes: 2

Related Questions