栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

Python

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Python

通过重写 __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
"""

 

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/938286.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号