Tom
Tom

Reputation: 16188

Reduce list based on index

Say I have 3 lists

x1 = [1, 2, 3, 4]
x2 = [2, 3, 4, 5]
x3 = [3, 4, 5, 6]

I would like to reduce this list of lists based on index.

We could reduce this by summing the elements: - x1[i] + x2[i] + x3[i]

out = [6, 9, 12, 15]

Or multiplying: - x1[i] * x2[i] * x3[i]

out = [6, 24, 60, 120]

What is the best way in python to accomplish this?

EDIT:

Is there a way of doing this for a list of lists?

Upvotes: 3

Views: 9401

Answers (2)

HYRY
HYRY

Reputation: 97281

Use zip(*data):

data = [
[1, 2, 3, 4],
[2, 3, 4, 5],
[3, 4, 5, 6]
]

print [sum(col) for col in zip(*data)]

import operator
def product(data):
    return reduce(operator.mul, data)

print [product(col) for col in zip(*data)]

If you want calculate with very large data, I suggest you use NumPy:

import numpy as np

print np.sum(data, axis=0)
print np.product(data, axis=0)

Upvotes: 3

Volatility
Volatility

Reputation: 32300

You can use the zip and sum functions.

out = [sum(i) for i in zip(x1, x2, x3)]

For multiplication you could use reduce (for Python 2)

out = [reduce(lambda a, b: a * b, i) for i in zip(x1, x2, x3)]

You can get reduce from functools in Python 3.

However, you could also define your own multiplication function, then use that function in the list comprehension.

def mult(lst):
    mul = 1
    for i in lst:
        mul *= i
    return mul

out = [mult(i) for i in zip(x1, x2, x3)]

If you have a list of lists lst = [[1, 2, 3, 4], [2, 3, 4, 5], [3, 4, 5, 6]] then all you need to do is replace zip(x1, x2, x3) with zip(*lst). The * operator basically unpacks the elements of the list and feeds them as separate arguments into the function.

For example:

out = [sum(i) for i in zip(*lst)]

Upvotes: 7

Related Questions