函数中的元组和

问题描述 投票:0回答:2

在一个python元组列表中,我需要找到每个首数和尾数的和。

例如

list = [(1, 4), (1, -4), (1, 4)]

而函数应该返回:(3, 4)

python list tuples series
2个回答
0
投票

试试。

data = [(1, 4), (1, -4), (1, 4)]
total_a = total_b = 0
for a,b in data:
    total_a += a
    total_b += b
print((total_a, total_b))

2
投票

你可以用以下方法来组合每个元组的索引 zip:

[sum(i) for i in zip(*list)]


1
投票

你可以通过以下方法来实现 numpy:

import numpy

tuple(sum(numpy.array(list)))
# (3, 4)

0
投票

您可以使用 reduce 从内置模块 functools:

from functools import reduce


l = [(1, 4), (1, -4), (1, 4)]
res = reduce(lambda x, y: (x[0] + y[0], x[1] + y[1]), l)
© www.soinside.com 2019 - 2024. All rights reserved.