简体   繁体   English

Python namedtuples 元素加法

[英]Python namedtuples elementwise addition

Is there a more pythonic way to implement elementwise addition for named tuples?是否有更 Pythonic 的方式来实现命名元组的元素加法?

Using this class that inherits from a namedtuple generated class named "Point I can do elementwise addition for this specific named tuple.使用继承自命名元组生成的名为“点”的类的类,我可以对这个特定的命名元组进行元素加法。

    class Point(namedtuple("Point", "x y")):
    def __add__(self, other):
        return Point(x = self.x + other.x, y = self.y + other.y)

If we use this functionality:如果我们使用这个功能:

print(Point(x = 1, y = 2) + Point(x = 3, y = 1))

The result is:结果是:

Point(x=4, y=3)

Is there a more pythonic way to do this in general?一般来说,有没有更蟒蛇的方式来做到这一点? Is there a generalized way to do this that can extend elementwise addition to all namedtuple generated objects?是否有一种通用的方法可以将元素添加扩展到所有 namedtuple 生成的对象?

(Named)tuples are iterable, so you could use map and operator.add . (命名)元组是可迭代的,因此您可以使用mapoperator.add Whether this is an improvement is debatable.这是否是一种改进是值得商榷的。 For 2D points, almost certainly not, but for higher-dimensional points, it would be.对于 2D 点,几乎可以肯定不是,但对于更高维点,它会是。

from operator import add


class Point(namedtuple("Point", "x y")):

    def __add__(self, other):
        return Point(*map(add, self, other))

This is a possible solution:这是一个可能的解决方案:

class Point(namedtuple("Point", "x y")):
    def __add__(self, other):
        return Point(**{field: getattr(self, field) + getattr(other, field)
                        for field in self._fields})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM