如何根据其值对对象列表进行排序

时间:2019-04-25 21:02:26

标签: python list sorting lambda

我正在尝试根据其值对对象列表进行排序。 我的银行清单包含硬币对象:

from decimal import *


class Coin:
    def __init__(self, coinValue):
        if coinValue in (
                Decimal('0.01'), Decimal('0.02'), Decimal('0.05'), Decimal('0.1'), Decimal('0.2'), Decimal('0.5'),
                Decimal('1'),
                Decimal('2'), Decimal('5')):
            self._coinValue = coinValue
        else:
            self._coinValue = 0

    def getCoinValue(self):
        return self._coinValue

它们是这样创建的:

x1 = Coin(Decimal("0.01"))
x2 = Coin(Decimal("0.02"))
x3 = Coin(Decimal("0.05"))
x4 = Coin(Decimal("0.1"))
x5 = Coin(Decimal("0.2"))
x6 = Coin(Decimal("0.5"))
x7 = Coin(Decimal("1"))
x8 = Coin(Decimal("2"))
x9 = Coin(Decimal("5"))
listOfCoins = [x1, x2, x3, x4, x5, x6, x7, x8, x9]

并以这种方式添加到银行:

bank = Bank()
for x in range(15):
    for i in listOfCoins:
        bank.addMoney(i)

我正在尝试对它进行排序:

class Bank:
    def __init__(self):
        self.bank = []

def addMoney(self, value):
    self.bank.append(value)

 def getSortedBankListWithCoins(self):
        return self.bank.sort(key=lambda x: x.getCoinValue(), reverse=True)

并这样调用:

listaCopy = self.bank.getSortedBankListWithCoins()
            for i in listaCopy:
                print(i.getCoinValue())

但是我有一个错误:

Traceback (most recent call last):
  File "C:\ProgramData\Anaconda3\lib\tkinter\__init__.py", line 1705, in __call__
    return self.func(*args)
  File "C:/Users/Admin/PycharmProjects/vending-machine/VendingMachine.py", line 270, in <lambda>
    command=lambda: proceedPurchasingItem(), height=1, width=7)
  File "C:/Users/Admin/PycharmProjects/vending-machine/VendingMachine.py", line 168, in proceedPurchasingItem
    labelFour.configure(text='Item: ' + format(container.purchaseItem(givenID)))
  File "C:\Users\Admin\PycharmProjects\vending-machine\Automat.py", line 74, in purchaseItem
    for i in listaCopy:
TypeError: 'NoneType' object is not iterable

1 个答案:

答案 0 :(得分:0)

我只需要做这样的事情:

def getSortedBankListWithCoins(self):
    self.bank.sort(key=lambda x: x.getCoinValue(), reverse=True)
    return self.bank

因为list.sort返回None。