我知道第二行是对的,但为什么第一行不对呢?出现以下错误:
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'
正如错误所说,您正试图访问
hnlist
(即hnlist.votes
)中的属性votes
。改为这样做:注意^{} 用于访问对象的属性,而不是获取字典的值
相关问题 更多 >
编程相关推荐