使一个类具有可比性,以便我可以获得列表中类实例的最大参数值(Python)

发布于 2025-01-13 23:49:39 字数 1225 浏览 6 评论 0原文

我有一个定义单个元素 (Request) 的类和另一个由 Request 实例组成的类 (RequestsBook)。 RequestsBook 还具有将更多请求附加到书中的方法。

class Request:
    def __init__(self, req_id, req_type, value):
        self.req_id = req_id
        self.req_type= req_type
        self.value = value

class RequestsBook:
    def __init__(self):
        self.requests_book = list()

    def add(self, new_req):
        self.requests_book.append(new_req)

    def get_max_value_of_type(self, req_type):
        # pass

如上所示,我想了解如何有效地获取 RequestsBook 列表中匹配的那些 Request 实例的最大特定类型

例如:

rb = RequestsBook()
rb.add(Request(1, 'A', 100))
rb.add(Request(2, 'B', 42))
rb.add(Request(3, 'A', 78))
rb.add(Request(4, 'A', 12))

rb.get_max_value_of_type('A') # should return 190
rb.get_max_value_of_type('B') # should return 42 

根据我的理解,我需要使用 functools.total_ordering 装饰器。

我以前从未使用过这个装饰器,并且正在努力想出一种有效的方法来实现 get_max_value_of_type 。遗憾的是,该用例的在线示例并不多。任何帮助将不胜感激。

I have a class that defines a single element (Request) and another class (RequestsBook) that is comprised from Request instances. The RequestsBook also has methods to append more requests into the book.

class Request:
    def __init__(self, req_id, req_type, value):
        self.req_id = req_id
        self.req_type= req_type
        self.value = value

class RequestsBook:
    def __init__(self):
        self.requests_book = list()

    def add(self, new_req):
        self.requests_book.append(new_req)

    def get_max_value_of_type(self, req_type):
        # pass

As seen above, I want to understand how I can efficiently get the maximum value of those Request instances inside the RequestsBook list that match a specific type.

For example:

rb = RequestsBook()
rb.add(Request(1, 'A', 100))
rb.add(Request(2, 'B', 42))
rb.add(Request(3, 'A', 78))
rb.add(Request(4, 'A', 12))

rb.get_max_value_of_type('A') # should return 190
rb.get_max_value_of_type('B') # should return 42 

Based on my understanding, I need to make the Request class comparable using the functools.total_ordering decorator.

I have never used this decorator before and I am struggling to think of an efficient way to implement get_max_value_of_type. Sadly, there are not many online examples for this use case. Any help will be much appreciated.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

霞映澄塘 2025-01-20 23:49:39

此代码按类型排序,然后按值排序,然后检索最大值作为最后一项。它使用 sorted 内置函数以及来自 operator 模块的 attrgetter 关键函数。它遵循 Python 文档 (3.10) 中的排序 HOWTO 教程中的说明。

from operator import attrgetter

class Request:
    def __init__(self,request=(None,None,None)):
        self.num, self.type, self.value = request

    def __repr__(self):
        return repr((self.num,self.type,self.value))

class RequestsBook(Request):
    def __init__(rb):
        Request.__init__(rb)
        rb.bklist = []
        rb.typetp = ('A','B','C')

    def sortattr(rb,l,a):
        return sorted(l,key=attrgetter(a))

    def maxtype(rb):
        typel = rb.sortattr(rb.bklist,'type')
        maxl = []
        for t in rb.typetp:
            tl = [req for req in typel if req.type == t]
            mtl = rb.sortattr(tl,'value')
            maxl.append(mtl[-1])
        return maxl           
    
inputl = [(1,'A',100),(2,'B',40),(3,'C',30),(4,'A',40),(5,'A',10),(6,'A',80),(7,'C',30),(8,'C',10),(9,'B',70),(10,'B',90)]
bk = RequestsBook()
bk.bklist = [Request(i) for i in inputl]
maxtypel = bk.maxtype()
print('input: ',inputl)
print('output: ',maxtypel)

This code sorts by type then sorts by value then retrieves the maximum as the last item. It uses sorted builtin with a key function, attrgetter from the operator module. It follows the explanation in the Sorting HOWTO tutorial in Python docs (3.10).

from operator import attrgetter

class Request:
    def __init__(self,request=(None,None,None)):
        self.num, self.type, self.value = request

    def __repr__(self):
        return repr((self.num,self.type,self.value))

class RequestsBook(Request):
    def __init__(rb):
        Request.__init__(rb)
        rb.bklist = []
        rb.typetp = ('A','B','C')

    def sortattr(rb,l,a):
        return sorted(l,key=attrgetter(a))

    def maxtype(rb):
        typel = rb.sortattr(rb.bklist,'type')
        maxl = []
        for t in rb.typetp:
            tl = [req for req in typel if req.type == t]
            mtl = rb.sortattr(tl,'value')
            maxl.append(mtl[-1])
        return maxl           
    
inputl = [(1,'A',100),(2,'B',40),(3,'C',30),(4,'A',40),(5,'A',10),(6,'A',80),(7,'C',30),(8,'C',10),(9,'B',70),(10,'B',90)]
bk = RequestsBook()
bk.bklist = [Request(i) for i in inputl]
maxtypel = bk.maxtype()
print('input: ',inputl)
print('output: ',maxtypel)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文