列表中的字典如何按照key排序

列表中的字典如何按照key排序

交易时间:2020-03-06 摘要:网转 金额:-5000.00 币种:人民币 余额:380.00

交易时间:2020-05-08 摘要:转入 金额:+500.00 币种:人民币 余额:880.00

交易时间:2020-08-10 摘要:消费 金额:-100.00 币种:人民币 余额:780.00

交易时间:2020-12-25 摘要:消费 金额:-101.00 币种:人民币 余额:679.00

交易时间:2021-01-05 摘要:转入 金额:+27800.00 币种:人民币 余额:28479.00



我想按照交易时间排序

正在回答 回答被采纳积分+1

登陆购买课程后可参与讨论,去登陆

1回答
时间, 2021-04-21 10:56:48

同学,你好!同学可以使用sort()方法排序,添加key参数设置排序条件

参考代码:

http://img1.sycdn.imooc.com//climg/607f94300981bf4214460549.jpg

祝学习愉快!

  • 提问者 eternityPython #1
    请帮忙看下我这段代码中querycount()方法的问题。

    # coding:utf-8

    class BankAccount(object):

    def __init__(self, init_money):
    self.total_money = init_money
    self.counts = []
    def querycount(self):
    print('===============================交易记录====================================')

           
        self.counts.sort(key=lambda x: x['交易时间'])
    for i in self.counts:

    print(i)

    def deposit(self, money, currency, des, deal_time_str):
    self.total_money += money
    msg = "交易时间:%s \t摘要:%s \t金额:+%.2f \t币种:%s \t余额:%.2f" % (deal_time_str, des, money, currency, self.total_money)
    print(msg)
    self.counts.append(msg)

    def withdraw(self, money, currency, des, deal_time_str):
    self.total_money -= money
    msg = "交易时间:%s \t摘要:%s \t金额:-%.2f \t币种:%s \t余额:%.2f" % (deal_time_str, des, money, currency, self.total_money)
    print(msg)
    self.counts.append(msg)


    if __name__ == "__main__":
    account = BankAccount(5380)
    account.withdraw(5000, "人民币", "网转", "2020-03-06")
    account.deposit(500, "人民币", "转入", "2020-05-08")
    account.withdraw(100, "人民币", "消费", "2020-08-10")
    account.withdraw(101.0, "人民币", "消费", "2020-12-25")
    account.deposit(27800, "人民币", "转入", "2021-01-05")
    account.querycount()


    2021-04-21 22:11:35
  • 提问者 eternityPython #2
    self.counts.reverse()
    for i in self.counts:
    print(i)

    这样就行了

    2021-04-21 22:51:45
  • 时间, 回复 提问者 eternityPython #3
    同学自己解决了问题,棒棒哒,继续加油。祝学习愉快~~~~
    2021-04-22 09:53:42
问题已解决,确定采纳
还有疑问,暂不采纳

恭喜解决一个难题,获得1积分~

来为老师/同学的回答评分吧

0 星
请稍等 ...
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号

在线咨询

领取优惠

免费试听

领取大纲

扫描二维码,添加
你的专属老师