2016-09-26 49 views
0

我正在学习如何使用类量排序的银行客户的功能,到目前为止,我已经实现了以下内容:创建一个由货币

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) 

我想创建一个排序的功能顾客所花费的金额,但不确定如何去做。

+0

你在哪里希望有这个功能吗?它不能在课堂上。它将在这堂课之外。这个函数将作为一个客户数组的输入。算法将运行在客户的财产上。创建代码的确切问题是什么?你是否希望使用预建的分类方法? – prabodhprakash

+0

你会排序* iterable /容器*,但你似乎还没有一个 –

+0

@prabodhprakash这正是我不确定的。 – ThatOnePythonNoob

回答

3

你可以通过这样的一个属性进行排序到位对象的列表:

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

-1
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 

简单的插入排序,接收客户数组并根据金钱排序。

此代码将超出您的客户类,将客户数组作为输入。

这个问题可以有很多正确的答案。书面插入排序来正确解释。

+0

他还没有客户列表。此外,不需要自己实现排序功能,因为python中的迭代器已经有很多可用的方法。 – Igle

+0

@Igle - 我在回答中特别提到,它是为了解释的目的,我写了插入排序。如果您在问题中阅读了我的评论,我已经提到过使用预先构建的方法。 – prabodhprakash

+0

@timgeb虽然你的眼睛可能会受到伤害,但问题并不在乎。这个人提出的问题对它来说是相当新颖的,这样写它的目的就是为了确保它尽可能精细! – prabodhprakash