立即学习:https://edu.csdn.net/course/play/26755/340128?utm_source=blogtoedu
如果列表元素是对象,如何排序:
1,为类添加__gt__ 或 __lt__ 方法
2,使用operator 库
实例代码:
class MyClass:
def __init__(self):
self.value = 0
'''
def __gt__(self, other): # 大于(>)
return self.value > other.value # 升序; 如想降序可改为 <
'''
'''
def __lt__(self, other): # 小于(<)
return self.value < other.value
'''
# 实例化
class1 = MyClass()
class1.value = 10
class2 = MyClass()
class2.value = 20
class3 = MyClass()
class3.value = 30
a = [class1, class2, class3]
# 排序(sort方法或者sorted函数)
# a.sort()
# b = sorted(a)
# 排序(operator 库, 此时不再需要内置方法)
import operator
a.sort(key=operator.attrgetter('value'), reverse=True)
# b = sorted(key=operator.attrgetter('value'))
# 如需降序可修改内置函数或者在sort方法或者sorted函数中令参数 reverse=True
print(a[0].value)
print(a[1].value)
print(a[2].value)
如果列表元素是字典,如何排序:
可使用lambda表达式
实例代码:
a = [
{'name':"Bob", 'age': 12},
{'name':"Torry", 'age': 9},
{'name':"Mary", 'age': 30}
]
print(a)
# 排序
b = sorted(a, key=lambda x: x['age']) # 使用字典中的'age'字段排序
print(b)
# 或者
a.sort(key=lambda x: x['age'], reverse=True) # 降序
print(a)