将元组添加到元组列表中

时间:2016-10-28 21:05:20

标签: python

如何将元组加到元组列表中,例如:

deploy-release

结果是:

>>> a = [(0, 1, 2), (3, 4, 5), (6, 7, 8)]
>>> b = (10, 20, 30)

我知道这可以通过numpy轻松解决:

>>> c 
[(10, 21, 32), (13, 24, 35), (16, 27, 38)]

但我宁愿避免numpy。

3 个答案:

答案 0 :(得分:4)

单行使用嵌套列表推导和魔术zip交错固定b三元组以添加到a的迭代元素,不需要任何numpy:

a = [(0, 1, 2), (3, 4, 5), (6, 7, 8)]
b = (10, 20, 30)

c = [tuple([i+j for i,j in zip(e,b)]) for e in a]
print(c)

结果:

[(10, 21, 32), (13, 24, 35), (16, 27, 38)]

编辑:如果不需要,您可以放弃tuple转换:

c = [[i+j for i,j in zip(e,b)] for e in a]

答案 1 :(得分:3)

您可以使用列表理解来执行此操作:

a = [(0, 1, 2), (3, 4, 5), (6, 7, 8)]
b = (10, 20, 30)
c = [[x + b[i] for i, x in enumerate(y)] for y in a]

c将是列表列表,而不是元组列表。如果这很重要,你可以这样做:

c = [tuple(x + b[i] for i, x in enumerate(y)) for y in a]

答案 2 :(得分:2)

定义一个函数来对两个向量求和:

def sum_vectors(a, b):
    return tuple(sum(z) for z in zip(a, b))

用它来定义一个向量列表添加向量的函数:

def add_vector_to_vectors(v, ws):
    return [sum_vectors(v, w) for w in ws]

使用示例:

>>> a = [(0, 1, 2), (3, 4, 5), (6, 7, 8)]
>>> b = (10, 20, 30)
>>> add_vector_to_vectors(b, a)
[(10, 21, 32), (13, 24, 35), (16, 27, 38)]