繁体   English   中英

元组或列表python上的元素明智加法

[英]Element-wise addition on tuple or list python

我想知道是否有人可以教我如何在不使用zip,numpy数组或任何这些模块的情况下在元组或列表上进行元素明智的加法?

例如,如果我有:

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

我如何获得: (3,1,0,2)而不是(1,0,0,1,2,1,0,1)

列表推导非常有用:

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

这可以通过简单地遍历列表的长度(假设两个列表的长度相等)并将两个列表中该索引处的值相加来完成。

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

您可以使用map函数,请参见此处: https : //docs.python.org/2/tutorial/datastructures.html#functional-programming-tools

map(func, seq)

例如:

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

如果两个列表的长度不同,将为您节省:

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

您可以使用operator.add

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

python3

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

这是一个适用于深层和浅层嵌套列表或元组的解决方案

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)
它( 默认情况下 )执行明智的元素加法,但是您可以指定更复杂的函数和/或lambda(前提是它们是二进制的)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM