在元组或列表python上添加元素

时间:2015-04-17 16:26:01

标签: python tuples

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

例如,如果我有:

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

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

6 个答案:

答案 0 :(得分:1)

List comprehensions非常有用:

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

答案 1 :(得分:0)

这可以通过简单地迭代列表的长度(假设两个列表具有相同的长度)并将两个列表中的索引的值相加来完成。

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

答案 2 :(得分:0)

您可以使用地图功能,请参阅此处: 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

答案 3 :(得分:0)

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

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

答案 4 :(得分:0)

您可以使用operator.add

执行此操作
from operator import add
>>>map(add, a, b)
[3, 1, 0, 2]

python3

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

答案 5 :(得分:0)

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

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(如果它们是二进制的)

相关问题