我对python中的“sorted()”有一个问题

2024-09-27 07:33:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我知道第二行是对的,但为什么第一行不对呢?出现以下错误:

def sort_stories_by_votes(hnlist):
    return sorted(hnlist, key= attrgetter(hnlist.votes), reverse=True)
    #return sorted(hnlist, key= lambda k:k['votes'], reverse=True)

我有这样的口述

hn.append({'title': title, 'link': href, 'votes': points})

这就是错误:

Traceback (most recent call last):
  File "C:\Users\LabComputer\Downloads\scrape.py", line 35, in <module>
    pprint.pprint(create_custom_hn(mega_links, mega_subtext))
  File "C:\Users\LabComputer\Downloads\scrape.py", line 33, in create_custom_hn
    return sort_stories_by_votes(hn)
  File "C:\Users\LabComputer\Downloads\scrape.py", line 20, in sort_stories_by_votes
    return sorted(hnlist, key= attrgetter(hnlist.votes), reverse=True)
AttributeError: 'list' object has no attribute 'votes'

Tags: keytruebyreturndownloadssortusersfile
1条回答
网友
1楼 · 发布于 2024-09-27 07:33:44

正如错误所说,您正试图访问hnlist(即hnlist.votes)中的属性votes。改为这样做:

from operator import itemgetter

def sort_stories_by_votes(hnlist):
    return sorted(hnlist, key=itemgetter("votes"), reverse=True)

注意^{}用于访问对象的属性,而不是获取字典的值

相关问题 更多 >

    热门问题