Moca
Moca

Reputation: 25

Iterate function over a list

I have a list in which total number of items may change. I want to apply a function which requires two inputs on first two items in the list and with the result I want to apply the same function on the third item in the list and with the result I want to apply function for fourth and so on...

Is there a better way to do the below when you know number of items in the list

for x,y,a,b,c...n in result:
    z=np.convolve(x,y)
    z=np.convolve(z,a)
    z=np.convolve(z,b)
    z=np.convolve(z,c)
    .
    .
    .
    final=np.convolve(z,n)
print(final)

Upvotes: 0

Views: 289

Answers (2)

vurmux
vurmux

Reputation: 10030

What you want to do is called reduce-function. Python has them.

For your case, you can use them like this:

from functools import reduce

reduce(lambda x, y: np.convolve(x, y), result)

Upvotes: 2

ForceBru
ForceBru

Reputation: 44886

You can do this:

for args in result:
    x, y, *others = args
    z = np.convolve(x,y)

    for a in others:
        z = np.convolve(z,a)

Upvotes: -1

Related Questions