py自定义列表四则运算
时间: 2023-07-09 09:08:26 浏览: 46
你可以通过创建一个自定义的 Python 类来实现自定义列表四则运算。以下是一个示例代码,其中定义了一个名为 CustomList 的类,它支持列表的加、减、乘和除:
```python
class CustomList:
def __init__(self, lst):
self.lst = lst
def __add__(self, other):
result = []
for i in range(len(self.lst)):
result.append(self.lst[i] + other.lst[i])
return CustomList(result)
def __sub__(self, other):
result = []
for i in range(len(self.lst)):
result.append(self.lst[i] - other.lst[i])
return CustomList(result)
def __mul__(self, other):
result = []
for i in range(len(self.lst)):
result.append(self.lst[i] * other.lst[i])
return CustomList(result)
def __truediv__(self, other):
result = []
for i in range(len(self.lst)):
result.append(self.lst[i] / other.lst[i])
return CustomList(result)
```
以上代码定义了一个名为 CustomList 的类,它包含一个 lst 属性,表示一个列表。该类还包含四个特殊方法:__add__、__sub__、__mul__ 和 __truediv__,分别对应加、减、乘和除运算。这些方法都接受另一个 CustomList 对象作为参数,并返回一个新的 CustomList 对象,表示运算结果。
使用该类,你可以创建两个 CustomList 对象,然后进行四则运算:
```python
a = CustomList([1, 2, 3])
b = CustomList([4, 5, 6])
c = a + b # [5, 7, 9]
d = a - b # [-3, -3, -3]
e = a * b # [4, 10, 18]
f = a / b # [0.25, 0.4, 0.5]
```