Reputation: 480
I want to create a new list (V) from other lists (a, b, c) and using a function, but I would like to take advantage of python and apply the function to the three lists and not element by element.
For example, I have the lists a, b and c; and the result after apply the function should be V. Thanks.
def mag(a, b, c):
# something sophisticated
return (a+b)*c
a = [1, 5, 7]
b = [4, 8, 3]
c = [2, 6, 3]
V = [10, 78, 30]
Upvotes: 1
Views: 252
Reputation: 6655
What about using only built-in functions? Like zip
>>> [mag(a_, b_, c_) for a_,b_,c_ in zip(a, b, c)]
[10, 78, 30]
Plus another python buit-in function, map which returns an iterator and thus makes things go faster and ends up saving memory:
>>> gen = map(lambda uple:mag(*uple), zip(a, b, c))
>>> list(gen)
[10, 78, 30]
Upvotes: 1
Reputation: 3801
An alternate solution is to use map
and lambda
In [16]: list(map(lambda p: mag(*p), zip(a, b, c)))
Out[16]: [10, 78, 30]
Upvotes: 1
Reputation: 106553
You can easily do this with the map
function:
V = list(map(mag, a, b, c))
Upvotes: 5