如何求元组中两点的和?

2024-10-17 21:49:48 发布

您现在位置:Python中文网/ 问答频道 /正文

有没有用“类点”求和两点

输入

a= (2,5)
b= (3,4)
c= a +b 

输出

^{pr2}$

Tags: pr2类点
3条回答

如果您想采用功能性方法:

t = tuple(map(sum, zip(a, b)))
import numpy
a = (2,5)
b = (3,4)
c = tuple(numpy.asarray(a) + numpy.asarray(b)) #Tuple convert is just because this is how your output defined. you can skip it...

您可以使用理解加zip

c = tuple(a_n + b_n for a_n, b_n in zip(a, b))

如果你需要做很多事情,这显然很麻烦(更不用说效率稍低)。如果要经常进行这种计算,那么最好使用numpy这样的库,它允许将数组作为一级对象添加。在

^{pr2}$

如果您使用numpy路径,那么在numpy数组和numpy数组之间转换有点开销,所以我建议您将点存储为数组而不是元组。在

相关问题 更多 >