学习笔记(10):Python 面试100讲(基于Python3.x)-如果列表元素是对象,如何排序?...

立即学习: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)

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值