我想知道是否有人可以教我如何在不使用 zip、numpy 数组或任何这些模块的情况下对元组或列表进行元素明智的添加?
例如如果我有:
a = (1,0,0,1)
b = (2,1,0,1)
我怎样才能得到:
(3,1,0,2)
而不是(1,0,0,1,2,1,0,1)
?
您可以使用
operator.add
来做到这一点
from operator import add
>>>map(add, a, b)
[3, 1, 0, 2]
在
python3
>>>list(map(add, a, b))
列表理解真的很有用:
[a[i] + b[i] for i in range(len(a))]
可以使用地图功能,看这里: 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))]
这可以通过简单地遍历列表的长度(假设两个列表的长度相等)并将两个列表中该索引处的值相加来完成。
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
这是一个适用于深层和浅层嵌套列表或元组的解决方案
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(前提是它们是二进制的)
>>> tuple(x+y for x,y in zip(a,b))
(3, 1, 0, 2)