Element-wise addition on tuple or list python

夙愿已清 提交于 2021-02-08 10:35:28

问题


I was wondering if anyone can teach me how to do element wise addition on a tuple or list without using zip, numpy arrays, or any of those modules?

For example if I have:

a = (1,0,0,1)
b = (2,1,0,1)

how can i get: (3,1,0,2) instead of (1,0,0,1,2,1,0,1) ?


回答1:


You can do this using operator.add

from operator import add
>>>map(add, a, b)
[3, 1, 0, 2]

In python3

>>>list(map(add, a, b))



回答2:


List comprehensions are really useful:

[a[i] + b[i] for i in range(len(a))]



回答3:


You can use the map function, see here: https://docs.python.org/2/tutorial/datastructures.html#functional-programming-tools

map(func, seq)

For example:

a,b=(1,0,0,1),(2,1,0,1)
c = map(lambda x,y: x+y,a,b)
print c



回答4:


This will save you if the length of both lists are not the same:

result = [a[i] + b[i] for i in range(min(len(a), len(b))]



回答5:


This can be done by simply iterating over the length of list(assuming both the lists have equal length) and adding up the values at that indices in both the lists.

a = (1,0,0,1)
b = (2,1,0,1)
c = (1,3,5,7)
#You can add more lists as well
n = len(a)
#if length of lists is not equal then we can use:
n = min(len(a), len(b), len(c))
#As this would not lead to IndexError
sums = []
for i in xrange(n):
    sums.append(a[i] + b[i] + c[i]) 

print sums



回答6:


Here is a solution that works well for deep as well as shallow nested lists or tuples

import operator
        def list_recur(l1, l2, op = operator.add):
            if not l1:
                return type(l1)([])
            elif isinstance(l1[0], type(l1)):
                return type(l1)([list_recur(l1[0], l2[0], op)]) + \
list_recur(l1[1:],l2[1:], op)
            else:
                return type(l1)([op(l1[0], l2[0])]) + \
list_recur(l1[1:], l2[1:], op)
It (by default) performs element wise addition, but you can specify more complex functions and/or lambdas (provided they are binary)

来源:https://stackoverflow.com/questions/29704668/element-wise-addition-on-tuple-or-list-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!