创建一个按金额对银行客户进行排序的函数

2024-05-14 06:32:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在学习如何使用课堂,到目前为止我已经取得了以下成就:

class customer:
    def __init__ (self, name, ID, money):
        self.name = name
        self.ID = ID
        self.money = money
    def deposit(self, amount):
        self.money = self.money+amount
    def withdraw(self, amount):
        self.money = self.money-amount

mike = customer('Mike', 1343, 1884883)
john = customer('John', 1343, 884839)
steve = customer('Steve', 1343, 99493)
adam = customer('Adam', 1343, 10000)

我想创建一个功能,根据客户拥有的资金量对其进行排序,但不确定如何进行排序。你知道吗


Tags: nameselfid排序initdefcustomeramount
2条回答
def sort_by_money(customer)
    for index in range(1,len(customer)):
        currentvalue = customer[index].money
        position = index

        while position>0 and customer[position-1].money > currentvalue:
            alist[position]=alist[position-1]
            position = position-1

        customer[position]=customer

简单的插入排序,接收customer数组并根据货币对其进行排序。你知道吗

此代码将在将customer数组作为输入的customer类之外。你知道吗

这个问题可以有许多正确答案。书面解释。你知道吗

可以按如下属性对在位对象列表进行排序:

your_list.sort(key=lambda x: x.attribute_name, reverse=True)

如果设置reverse=False,则列表按升序排列,其中reverse=True按从最高到最低的顺序排列。你知道吗

所以在你的情况下:

class customer:
    def __init__ (self, name, ID, money):
        self.name = name
        self.ID = ID
        self.money = money
    def deposit(self, amount):
        self.money = self.money+amount
    def withdraw(self, amount):
        self.money = self.money-amount


mike = customer('Mike', 1343, 1884883)
john = customer('John', 1343, 884839)
steve = customer('Steve', 1343, 99493)
adam = customer('Adam', 1343, 10000)

unsorted_list = [steve, adam, mike, john]

print [c.name for c in unsorted_list]

unsorted_list.sort(key=lambda c: c.money, reverse=True)

print [c.name for c in unsorted_list]

For more information check this question too

相关问题 更多 >