python - 当我尝试对列表进行排序时,出现错误 'dict' 对象没有属性

标签 python list sorting dictionary

我创建列表的代码是:

choices = []
for bet in Bet.objects.all():
    #...
    #Here is code that skip loop if bet.choice exist in choices[]
    #...
    temp = {
        'choice':bet.choice,
        'amount':bet.sum,
        'count':bets.filter(choice=bet.choice).count()}
    choices.append(temp)

choices.sort(key=attrgetter('choice'), reverse=True)
choices.sort(key=attrgetter('amount'), reverse=True)
choices.sort(key=attrgetter('count'), reverse=True)

我必须按列表排序,因为模型 orderby() 不能按 count() 排序,可以吗?

最佳答案

您的词典没有choiceamountcount 属性。这些是,因此您需要改用itemgetter() 对象。

from operator import itemgetter

choices.sort(key=itemgetter('choice'), reverse=True)
choices.sort(key=itemgetter('amount'), reverse=True)
choices.sort(key=itemhetter('count'), reverse=True)

如果要按多个条件排序,只需排序一次,条件按顺序命名:

choices.sort(key=itemgetter('count', 'amount', 'choice'), reverse=True)

但是,您可能希望让数据库 进行排序。

关于python - 当我尝试对列表进行排序时,出现错误 'dict' 对象没有属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34042961/

相关文章:

android - 如何通过将其他对象字段保存为索引来按对象字段对 MutableMap 进行排序?

python - 如何在 Django 模板中放置链接

python - 在 Python 中使用 fping 获取 ping 时间

php - 需要帮助将我漂亮的 soup (Python) 代码转换为 PHP

c# - 字典<整数,列表<字符串>>

java - 使用哈希码对对象的 ArrayList 进行排序

python - picamera:在后台连续捕捉的同时捕捉一帧

python - 命名列表列表

python - 将列表中所有可能的对象配对

Javascript Case Insensitive Sort objects containing undefined 作为值