按两个属性对对象进行排序

时间:2018-12-12 12:34:02

标签: python list sorting oop

我试图主要根据一个属性对对象进行排序,但是如果另一个属性相同,则还应该考虑第二个属性。从元组比较中得到想法后,我尝试了以下操作:

但是,它不能像这样工作。知道我在做什么错吗?

class Customer(object):

    def __init__(self, name, balance, value):
        self.name = name
        self.balance = balance
        self.value = value




list_not_sorted = []
print(list_not_sorted)
c1 = Customer("c1", 10, 20)
c2 = Customer("c2", 10, 40)
c3 = Customer("c3", 10, 50)
c4 = Customer("c4", 30, 0)
c5 = Customer("c5", 40, 10)
c6 = Customer("c6", 40, 20)
c7 = Customer("c7", 70, 10)

list_not_sorted.append(c1)
list_not_sorted.append(c2)
list_not_sorted.append(c3)
list_not_sorted.append(c4)
list_not_sorted.append(c5)
list_not_sorted.append(c6)
list_not_sorted.append(c7)

def key_selection(ls):
        return(ls.balance, ls.value)

list_sorted = sorted(list_not_sorted, key=lambda k: key_selection(k))

print(list_sorted[1].name)
#expected_result = [c7, c6, c5, c4, c3, c2, c1]

0 个答案:

没有答案