![](/img/trans.png)
[英]Python: How do I make two time arrays with different units comparable?
[英]How do I make my class comparable in Python?
我有一個 Pair class (它有一個鍵和一個值),我正在嘗試制作一個程序來創建一堆 Pair 對象,將它們添加到列表中,並對它們執行穩定的快速排序。 但是,我似乎不知道如何使對象具有可比性,以便程序在兩個對象具有相同值時自動比較它們的鍵。 在 Java 中很容易做到這一點,但我只是不明白我應該如何在 Python 中做同樣的事情。
先感謝您!
class Pair(Generic[K,V]):
def __init__(self, key: K, val: V):
self.key = key
self.value = val
以下內容如何(可按鍵排序,但您可以輕松定義任何其他方式對它們進行排序):
class Pair:
def __init__(self, key, val):
self.key = key
self.value = val
def __eq__(self, other: "Pair"):
return self.key == other.key
def __lt__(self, other: "Pair"):
return self.key < other.key
def __le__(self, other: "Pair"):
return self.key <= other.key
def __gt__(self, other: "Pair"):
return self.key > other.key
def __ge__(self, other: "Pair"):
return self.key >= other.key
def __str__(self):
return f"{self.key}={self.value}"
def __repr__(self):
return f"{self.key}={self.value} ({id(self)})"
test = [
Pair("a2", "1"), Pair("a1", "2"), Pair("b1", "3"),Pair("br", "4")
]
print(sorted(test))
Output:
$ python3 ~/tmp/test.py
[a1=2 (4352627216), a2=1 (4352622288), b1=3 (4352627344), br=4 (4352627408)]
要按值排序,然后在值相等時按鍵排序,您將 dp 類似:
def __lt__(self, other: "Pair"):
if self.value != other.value:
return self.value < other.value
return self.key < other.key
具有上述lt
的示例輸入/輸出:
# Input
test = [
Pair("a2", "1"), Pair("a1", "2"), Pair("b1", "1"),Pair("br", "4")
]
# Output
[a2=1 (4466773648), b1=1 (4466778768), a1=2 (4466778640), br=4 (4466778832)]
此外,如果您計划將這些對用作字典鍵或集合,您可以實現__hash__
。 更多運營商請看這里
Python 為此使用了所謂的“dunder 方法”(雙下划線方法)。 您已經在使用 init dunder 方法。 定義__eq__
。
編輯:參見優秀的 dbader 文章
我們還可以使用@functools.total_ordering
class 裝飾器來減少 class 方法的數量。 如鏈接的 Python 文檔頁面中所述:
這簡化了指定所有可能的豐富比較操作所涉及的工作。 class 必須定義lt ()、 le ()、 gt () 或ge () 之一。 此外,class 應提供eq () 方法。
有了這個,實現將如下所示:
from functools import total_ordering
@total_ordering
class Pair:
def __init__(self, key, val):
self.key = key
self.value = val
def __eq__(self, other):
return self.key == other.key
def __lt__(self, other):
return self.key < other.key
def __repr__(self):
return self.key.__repr__() + ': ' + self.value.__repr__()
pairs = [Pair(1, 'one'), Pair(2, 'two'), Pair(3, 'three')]
print(sorted(pairs))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.