只能concatenate list(不是"Point") to list In adding and subtracting points in python
can only concatenate list (not "Point") to list In adding and subtracting points in python
我正在尝试执行以下任务:
对于两个点 (1,1)+(2,2)=(1+2,1+2)
我执行了这段代码:
class Point(object):
def __init__(self, x, y):
self.x = x
self.y = y
def __repr__(self):
return "Point({0}, {1})".format(self.x, self.y)
def __add__(self, other):
return [self.x + other.x, self.y + other.y]
def __sub__(self, other):
return [self.x - other.x, self.y - other.y]
当我尝试 运行 下面的代码时,它说:
from functools import reduce
def add_sub_results(points):
points = [Point(*point) for point in points]
return [str(reduce(lambda x, y: x + y, points)),
str(reduce(lambda x, y: x - y, points))]
它returns
return [str(reduce(lambda x, y: x + y, points)),
5 str(reduce(lambda x, y: x - y, points))]
6
TypeError: can only concatenate list (not "Point") to list
我该如何解决这个问题?
我认为你的 __add__()
和 __sub__()
方法 Point
class 应该是:
class Point(object):
...
def __add__(self, other):
return Point(self.x + other.x, self.y + other.y) #<-- MODIFIED THIS
def __sub__(self, other):
return Point(self.x - other.x, self.y - other.y) #<-- MODIFIED THIS
我正在尝试执行以下任务: 对于两个点 (1,1)+(2,2)=(1+2,1+2)
我执行了这段代码:
class Point(object):
def __init__(self, x, y):
self.x = x
self.y = y
def __repr__(self):
return "Point({0}, {1})".format(self.x, self.y)
def __add__(self, other):
return [self.x + other.x, self.y + other.y]
def __sub__(self, other):
return [self.x - other.x, self.y - other.y]
当我尝试 运行 下面的代码时,它说:
from functools import reduce
def add_sub_results(points):
points = [Point(*point) for point in points]
return [str(reduce(lambda x, y: x + y, points)),
str(reduce(lambda x, y: x - y, points))]
它returns
return [str(reduce(lambda x, y: x + y, points)),
5 str(reduce(lambda x, y: x - y, points))]
6
TypeError: can only concatenate list (not "Point") to list
我该如何解决这个问题?
我认为你的 __add__()
和 __sub__()
方法 Point
class 应该是:
class Point(object):
...
def __add__(self, other):
return Point(self.x + other.x, self.y + other.y) #<-- MODIFIED THIS
def __sub__(self, other):
return Point(self.x - other.x, self.y - other.y) #<-- MODIFIED THIS