Python类和列表过滤器

2024-09-27 21:28:43 发布

您现在位置:Python中文网/ 问答频道 /正文

为了达到这一点,我正在学习如何操作课程和列表理解,我遇到了这个问题:

class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

def are_in_first_quadrant(listPoint):
    newListPoint = filter(lambda pnt: pnt.x > 0 and pnt.y > 0, listPoint)
    return newListPoint

pList = [Point(-3,7), Point(2,3), Point(7,0), Point(6,-9), Point(7,9)]
    newList = are_in_first_quadrant(pList)

因此,您可以看到,这是为了列出第一个象限中的点的列表,但是当我尝试打印“newList”时,我得到:

^{pr2}$

而不是:

[Point(2,3) , Point(7.9)]

查看此帖子:Filters in Python3
我知道打印出来的是内存位置,但我并没有从中得到更多。在

所以问题是我到底该怎么解决这个问题?
我想这可能与我如何使用lambda有关,但也不太确定。
我使用的是python2.7

提前谢谢。在

编辑:
也刚试过

def are_in_first_quadrant(listPoint):
    newListPoint = [pnt for pnt in listPoint if pnt.x > 0 and pnt.y > 0]
    return newListPoint

它会吐出同样的东西。在


Tags: andlambdainself列表returndefare
1条回答
网友
1楼 · 发布于 2024-09-27 21:28:43

您需要为您的Point类提供一个^{} method

class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __repr__(self):
        return "Point({}, {})".format(self.x, self.y)

打印列表时,将为每个元素调用此方法。在

请注意:一个名为are_...(或is_...)的函数应该返回True或{}。更合适的名称是points_in_first_quadrant()。在

有关__str__()和{}之间的比较,请参见this question。在

相关问题 更多 >

    热门问题