【问题标题】:When I tried to sort a list, I got an error 'dict' object has no attribute当我尝试对列表进行排序时,出现错误“dict”对象没有属性
【发布时间】:2016-03-06 16:58:29
【问题描述】:

我创建列表的代码是:

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() 排序,可以吗?

【问题讨论】:

  • 请发布(并阅读)完整的错误。
  • @skyking: AttributeError: 'dict' object has no attribute 'choice'..
  • 这意味着dict 对象没有choice 属性。实际上阅读错误消息并考虑一下是排除故障时的良好开端。事实证明,缺少该属性的是列表的元素。

标签: python list sorting dictionary


【解决方案1】:

您的字典没有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)

不过,您可能希望 数据库 进行排序。

【讨论】:

  • 哦!现在是工作。我还有更多问题,我在选择 = sorted(choices.items(), key=itemgetter(1)) 之前尝试了这个,但它没有用
  • @ZeroOHo:那是因为choices 是一个字典列表。列表没有 .items() 方法。
猜你喜欢
  • 2021-12-04
  • 2019-10-18
  • 1970-01-01
  • 1970-01-01
  • 2015-08-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-14
相关资源
最近更新 更多