如何创建逻辑复杂的自定义排序函数?

2024-03-28 11:12:11 发布

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

我尝试根据一些非平凡的比较逻辑对对象列表进行排序,但发现很困难,因为在Python中,自定义排序函数只需要一个参数。例如,在Java中,sort函数会有对object1object2的引用,这样比较它们就很简单了。你知道吗

class Point:
    def __init__(self, char, num, pt_type):
        self.char = char
        self.num = num
        self.pt_type = pt_type  # 'start' or 'end'

    def __str__(self):
        return str([self.char, str(self.num), self.pt_type])
    def __repr__(self):
        return str(self)

arr = [Point('C', 1, 'end'), Point('C', 9, 'start'),
       Point('B', 7, 'end'), Point('B', 2, 'end'),
       Point('A', 3, 'start'), Point('A', 6, 'start')]

def my_sort(key):
    # Sort by first element (letter). 
    #
    # If the letter is the same, fallback to sorting by the
    # 2nd element (number), but the logic of this comparison depends
    # on `pt_type`:
    #   -If Point1 and Point2 both have type 'start', pick the higher number first.
    #   -If Point1 and Point2 both have type 'end', pick the lower number first.
    #   -If Point1 and Point2 have different types, pick the 'start' type first.
    return key.char

print(sorted(arr, key=my_sort))

预期的排序顺序应为:

[Point('A', 6, 'start'), Point('A', 3, 'start')
 Point('B', 2, 'end'), Point('B', 7, 'end'),
 Point('C', 9, 'start'), Point('C', 1, 'end')]

我甚至不知道如何开始实现所需的逻辑,所以如果能朝着正确的方向努力,我将不胜感激。你知道吗


Tags: theselfptif排序deftypesort
1条回答
网友
1楼 · 发布于 2024-03-28 11:12:11

您可以将排序作为类的属性,然后使用sorted。这种方法的好处是:无需额外的努力,您就可以通过比较运算符(如><==)相互比较对象。你知道吗

指定__eq____lt__方法

至少应该指定__eq____lt__方法:

class Point:
    def __init__(self, char, num, pt_type):
        self.char = char
        self.num = num
        self.pt_type = pt_type  # 'start' or 'end'

    def __str__(self):
        return str([self.char, str(self.num), self.pt_type])

    def __repr__(self):
        return str(self)

    def __eq__(self, other):
        return self.char == other.char and self.pt_type == other.pt_type

    def __lt__(self, other):
        if self.char != other.char:
            return self.char < other.char
        if (self.pt_type == 'start') and (other.pt_type == 'start'):
            return self.num > other.num
        elif (self.pt_type == 'end') and (other.pt_type == 'end'):
            return self.num < other.num
        else:
            return self.pt_type == 'start'

添加其他比较方法,例如__gt____ge__等,可以通过^{}简化:

from functools import total_ordering

@total_ordering
class Point:
    def __init__(self, ...):
        # initialization logic
    def __eq__(self, other):
        # as before
    def __lt__(self, other):
        # as before

示例

arr = [Point('C', 1, 'end'), Point('C', 9, 'start'),
       Point('B', 7, 'end'), Point('B', 2, 'end'),
       Point('A', 3, 'start'), Point('A', 6, 'start')]

print(sorted(arr))

[['A', '6', 'start'],
 ['A', '3', 'start'],
 ['B', '2', 'end'],
 ['B', '7', 'end'],
 ['C', '9', 'start'],
 ['C', '1', 'end']]
网友
2楼 · 发布于 2024-03-28 11:12:11

我将使用以下key函数:

class Point:
    def __init__(self, char, num, pt_type):
        self.char = char
        self.num = num
        self.pt_type = pt_type  # 'start' or 'end'

    def __str__(self):
        return str([self.char, str(self.num), self.pt_type])

    def __repr__(self):
        return str(self)


arr = [Point('C', 1, 'end'), Point('C', 9, 'start'),
       Point('B', 7, 'end'), Point('B', 2, 'end'),
       Point('A', 3, 'start'), Point('A', 6, 'start')]


def key(p):
    return p.char, int(p.pt_type != 'start'), p.num if p.pt_type == 'end' else -1 * p.num


result = sorted(arr, key=key)
print(result)

输出

[['A', '6', 'start'], ['A', '3', 'start'], ['B', '2', 'end'], ['B', '7', 'end'], ['C', '9', 'start'], ['C', '1', 'end']]

key函数创建一个元组用作键,第一个元素是字母,如果节点类型为“start”,则第二个元素为0,如果节点类型为“end”,则为1。最后一个元素的类型为“start”时为负,类型为“end”时为正。你知道吗

网友
3楼 · 发布于 2024-03-28 11:12:11

您想使用cmp参数来sorted,它接受两个参数的比较函数: https://docs.python.org/2/library/functions.html#sorted

作为参考,key函数将从每个被排序的项中计算一个派生值,并根据该值进行排序,例如,要按对中的第二个值对一个对列表进行排序,可以执行:sorted(items, key=lambda x: x[1])

相关问题 更多 >