定义一个类SecondarySortKey,实现自定义的用于排序的key
时间: 2023-05-31 22:02:26 浏览: 53
SecondarySortKey类的定义如下:
```python
class SecondarySortKey:
def __init__(self, first_key, second_key):
self.first_key = first_key
self.second_key = second_key
def __lt__(self, other):
if self.first_key < other.first_key:
return True
elif self.first_key > other.first_key:
return False
else:
return self.second_key < other.second_key
def __eq__(self, other):
return self.first_key == other.first_key and self.second_key == other.second_key
```
该类接受两个参数,分别为第一关键字和第二关键字。在比较时,如果第一关键字不同,则按照第一关键字排序;如果第一关键字相同,则按照第二关键字排序。通过实现__lt__方法和__eq__方法,可以将SecondarySortKey对象用于排序。例如:
```python
data = [(1, 2), (2, 1), (1, 3), (2, 2)]
sorted_data = sorted(data, key=lambda x: SecondarySortKey(x[0], x[1]))
print(sorted_data)
```
输出:
```
[(1, 2), (1, 3), (2, 1), (2, 2)]
```
在这个例子中,我们将一个包含元组的列表按照元组的第一个元素和第二个元素进行排序,得到了按照第一关键字升序、第二关键字升序的排序结果。