You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python重载算术与比较运算符实现列表逐元素运算

实现方案

核心逻辑:Python原生list类型的运算符无法直接修改重载,因此需要先自定义一个支持逐元素运算的序列包装类,在Data类初始化时将字典中存储的原生列表替换为该包装类的实例,再为包装类重载对应的算术、比较运算符即可。


实现思路

  • 先定义逐元素运算的列表包装类,重载需要的魔术方法:
    • 加法__add__:兼容「列表+标量」「列表+等长列表」两种场景
    • 反向加法__radd__:支持标量在加号左侧的写法(比如2 + objA.data['a'])
    • 大于比较__gt__:实现逐元素大小比较,返回布尔值列表
      其他运算符(减法、乘法、小于、等于之类的)逻辑完全一致,照着加法的写法扩展即可。
  • 改造Data类初始化逻辑:初始化时遍历传入的字典,将所有列表值包装为上述自定义类的实例,存入self.data。

完整可运行代码

class ElementWiseList:
    def __init__(self, raw_list: list):
        self._list = raw_list

    def __add__(self, other):
        # 处理和列表/同类型实例相加的情况
        if isinstance(other, (list, ElementWiseList)):
            other_list = other._list if isinstance(other, ElementWiseList) else other
            if len(self._list) != len(other_list):
                raise ValueError("逐元素运算的两个列表长度必须一致")
            return ElementWiseList([a + b for a, b in zip(self._list, other_list)])
        # 处理和数字标量相加的情况
        elif isinstance(other, (int, float)):
            return ElementWiseList([item + other for item in self._list])
        else:
            raise TypeError(f"不支持ElementWiseList和{type(other)}类型做加法运算")
    
    def __radd__(self, other):
        # 反向加法直接复用__add__逻辑,适配加法交换律
        return self.__add__(other)
    
    def __gt__(self, other):
        # 大于比较,兼容和标量、等长列表比较
        if isinstance(other, (list, ElementWiseList)):
            other_list = other._list if isinstance(other, ElementWiseList) else other
            if len(self._list) != len(other_list):
                raise ValueError("逐元素比较的两个列表长度必须一致")
            return ElementWiseList([a > b for a, b in zip(self._list, other_list)])
        elif isinstance(other, (int, float)):
            return ElementWiseList([item > other for item in self._list])
        else:
            raise TypeError(f"不支持ElementWiseList和{type(other)}类型做大于比较")
    
    def __repr__(self):
        # 打印时直接展示内部列表内容,和原生列表表现一致
        return repr(self._list)


class Data:
    def __init__(self, data: dict):
        # 初始化时把字典里的列表值统一包装成支持逐元素运算的实例
        self.data = {}
        for key, value in data.items():
            if isinstance(value, list):
                self.data[key] = ElementWiseList(value)
            else:
                self.data[key] = value

效果验证

运行测试代码:

d = {'a': [1, 2, 3], 'b':[4, 5, 6]}
objA = Data(d)
print(objA.data['a'] + 2)               # 输出 [3, 4, 5]
print(objA.data['a'] + objA.data['b'])  # 输出 [5, 7, 9]
print(objA.data['a'] > 2)               # 输出 [False, False, True]

返回结果和预期完全一致。如果需要支持更多运算(减法、乘法、等于比较、小于比较等),只需要在ElementWiseList类里按照__add__、__gt__的写法,补充实现__sub__、__mul__、__eq__、__lt__等对应魔术方法即可。

内容的提问来源于stack exchange,提问作者Asmita Poddar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.28 07:42:14