怎么才能把结果放到一个Vector tuple里: Vector(3,5)
回复“资源”即可获赠Python学习资料
大家好,我是皮皮。
一、前言
前几天在Python最强王者交流群有个叫【Chloe】的粉丝问了一个Python基础的问题,这里拿出来给大家分享下,一起学习下。

代码如下:
class Vector:
def __init__(self, *args):
self.components = args
def __repr__(self):
return f"Vector{self.components}"
def __str__(self):
return f'{self.components}'
def __len__(self):
return len(self.components)
def __add__(self,other):
t = tuple(zip(self.components, other.components))
for i,j in t:
print(i+j)
v1 = Vector(4,2)
v2 = Vector(-1,3)
v1+v2
目前的结果是: 3 5
二、解决过程
这里【瑜亮老师】给出了一个代码,如下所示:
def __add__(self,other):
t = tuple(zip(self.components, other.components))
print(tuple(i+j for i,j in t))
不过看上去
tuple
有些冗余,直接 t = zip(self.components, other.components)
因为zip
的结果就是tuple
类型的。
后来月神又给了一个代码,如下所示:
def __add__(self,other):
t = map(lambda x,y: x+y, self.components, other.components)
return Vector(*t)

有人还怀疑题目就是【月神】出的,哈哈哈哈。
结合【月神】和【瑜亮老师】的写法,【Chloe】自己举一反三,写了一份代码,如下所示:
def __add__(self,other):
# method1:
zipped = zip(self.components, other.components)
t = tuple(i+j for i,j in zipped)
return Vector(*t)
看来确实是学习到位了!
三、总结
大家好,我是皮皮。这篇文章主要盘点一个Python基础问题,文中针对该问题给出了具体的解析和代码演示,帮助粉丝顺利解决了问题。
最后感谢粉丝【Chloe】提问,感谢【瑜亮老师】、【月神】给出的具体解析和代码演示,感谢粉丝【东哥】、【dcpeng】、【老松鼠】、【炸蛋散】等人参与学习交流。
小伙伴们,快快用实践一下吧!如果在学习过程中,有遇到任何问题,欢迎加我好友,我拉你进Python学习交流群共同探讨学习。
------------------- End -------------------
往期精彩文章推荐:

欢迎大家点赞,留言,转发,转载,感谢大家的相伴与支持
想加入Python学习群请在后台回复【入群】
万水千山总是情,点个【在看】行不行
评论