python对class排序
时间: 2023-07-25 16:43:27 浏览: 47
Python的类是对象,它们不会被排序。但是,你可以在类中定义一个比较方法,以便在列表中对实例进行排序。例如,如果你有一个Person类,可以按年龄对它们进行排序:
```python
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __repr__(self):
return f"{self.name} ({self.age})"
def __lt__(self, other):
return self.age < other.age
people = [Person("Alice", 25), Person("Bob", 30), Person("Charlie", 20)]
sorted_people = sorted(people)
print(sorted_people)
```
这将输出 `[Charlie (20), Alice (25), Bob (30)]`,这是按年龄排序的Person对象的列表。
相关问题
python对数据排序
Python中提供了多种排序方法,可以根据需求选择不同的方法。下面是几种常用的排序方法:
1. 使用内置函数`sorted()`对列表进行排序:
```python
list1 = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]
sorted_list1 = sorted(list1)
print(sorted_list1) # [1, 1, 2, 3, 3, 4, 5, 5, 5, 6, 9]
```
2. 使用列表对象的`sort()`方法对列表进行排序:
```python
list2 = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]
list2.sort()
print(list2) # [1, 1, 2, 3, 3, 4, 5, 5, 5, 6, 9]
```
3. 对字典进行排序,可以使用内置函数`sorted()`结合字典的`items()`方法:
```python
dict1 = {'a': 3, 'c': 1, 'b': 2}
sorted_dict1 = sorted(dict1.items())
print(sorted_dict1) # [('a', 3), ('b', 2), ('c', 1)]
```
4. 对列表中的对象进行排序,可以使用`key`参数指定排序的关键字,例如:
```python
class Student:
def __init__(self, name, score):
self.name = name
self.score = score
def __repr__(self):
return f"Student(name={self.name}, score={self.score})"
students = [
Student("Tom", 90),
Student("Jerry", 80),
Student("Bob", 95),
]
# 按照分数从高到低排序
sorted_students = sorted(students, key=lambda x: x.score, reverse=True)
print(sorted_students) # [Student(name=Bob, score=95), Student(name=Tom, score=90), Student(name=Jerry, score=80)]
```
python 自定义 class 类的排序
可以通过在类中定义 __lt__ 方法来实现自定义排序。例如,可以定义一个 Person 类,其中包含 name 和 age 两个属性,然后通过比较 age 属性来进行排序:
```
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __lt__(self, other):
return self.age < other.age
```
然后可以创建一个 Person 对象列表,使用 sorted 函数进行排序:
```
people = [Person('Alice', 25), Person('Bob', 30), Person('Charlie', 20)]
sorted_people = sorted(people)
for person in sorted_people:
print(person.name, person.age)
```
输出结果为:
```
Charlie 20
Alice 25
Bob 30
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)