gpt4 book ai didi

python - python元组列表中每个元素的总和

转载 作者:太空宇宙 更新时间:2023-11-03 12:17:44 25 4
gpt4 key购买 nike

我想添加包含元组的列表的每个元素。例如,

    >>> list1
[(0, 1, 2), (3, 4, 5), (6, 7, 8)]
>>> list2
[(1, 2, 3), (4, 5, 6), (7, 8, 9)]

答案应该是

     list3 = [(1,3,5),(7,9,11),(13,15,17)]

最佳答案

zip 是你的 friend 。

result = []
for ta, tb in zip(list1, list2):
t =tuple(a+b for a, b in zip(ta, tb))
result.append(t)

print result
>> [(1,3,5),(7,9,11),(13,15,17)]

或更多 pythonic 是:

result = [tuple(a+b for a, b in zip(ta, tb)) for ta, tb in zip(list1, list2)]
print result
>> [(1,3,5),(7,9,11),(13,15,17)]

通过这样做,结果可以简单地成为一个生成器:

result = (tuple(a+b for a, b in zip(ta, tb)) for ta, tb in zip(list1, list2))

关于python - python元组列表中每个元素的总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9404245/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com