python - Reduce list based on index -


say have 3 lists

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

i reduce list of lists based on index.

we reduce summing 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 best way in python accomplish this?

edit:

is there way of doing list of lists?

you can use zip , sum functions.

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

for multiplication use reduce (for python 2)

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

you can reduce functools in python 3.

however, define own multiplication function, use function in list comprehension.

def mult(lst):     mul = 1     in lst:         mul *=     return mul  out = [mult(i) in zip(x1, x2, x3)] 

if have list of lists lst = [[1, 2, 3, 4], [2, 3, 4, 5], [3, 4, 5, 6]] need replace zip(x1, x2, x3) zip(*lst). * operator unpacks elements of list , feeds them separate arguments function.

for example:

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

Comments

Popular posts from this blog

get url and add instance to a model with prefilled foreign key :django admin -

css - Make div keyboard-scrollable in jQuery Mobile? -

ruby on rails - Seeing duplicate requests handled with Unicorn -