Python __lt__ 自定义排序

通过重写 __lt__ 方法,可以达到类似于Java中compareTo的效果 

class Fruit:
    def __init__(self, name, count, money):
        self.name = name
        self.count = count
        self.money = money

    def __lt__(self, other):
        if self.money == other.money:  # money 相同比较 count,count 也相同则比较 name
            if self.count == other.count:
                return self.name < other.name # 升序
            return self.count > other.count # 降序
        return self.money > other.money # 降序


fruit = []
while True:
    data = input().split(' ')
    if data[0] == 'None':
        break
    for i in fruit:
        if i.name == data[0]:
            i.count += 1
            i.money += float(data[1])
            break
    else:
        # src = {'name': data[0], 'count': 1, 'money': float(data[1])}
        src = Fruit(data[0], 1, float(data[1]))
        fruit.append(src)


sum_money = 0
avg_money = 0
all_count = 0
max_count = fruit[0].count
fruit.sort()
for i in fruit:
    sum_money += i.money
    all_count += i.count
    if max_count < i.count:
        max_count = i.count
    print(i.name + ' ' + str(i.count) + ' ' + str(i.money))

avg_money = sum_money / all_count
print(round(avg_money, 2))

for i in fruit:
    if max_count == i.count:
        print(i.name)


"""
apple 25.0
pear 8.0
apple 5.0
pear 2.0
banana 10.0
orange 30.0
None
"""

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值