Django / Python不顺序类型:complex()< complex()Django教程youtube-croach [英] Django/Python unorderable types: complex() < complex() Django tutorial youtube-croach
问题描述
我正在从教程中学习Django和Python,大多数时候Django或Python的不同版本之间存在错误。
I'm learning Django and Python from tutorial, and most of the time there are bugs between different version of Django or Python.
我遇到这个问题不顺序类型:complex()< complex()因为这样:
I ran into this problem "unorderable types: complex() < complex()" because of this :
def top_stories(top=180, consider=1000):
latest_stories = Story.objects.all().order_by('-created_at')[:consider]
ranked_stories = sorted([(score(story), story) for story in latest_stories], reverse=True)
return [story for score, story in ranked_stories][:top]
我找到一个解决方案,说:
使用一个关键功能给商店一个分数:
I found a solution that said: Use a key function to give stores a score:
ranked_stories = sorted(latest_stories, key=score, reverse=True)
return ranked_stories[:top]
这个消除了您正在使用的装饰排序不理想的图案的需要,并且还高兴地避免了比较单个Story实例而无需订购支持。
This removes the need for a decorate-sort-undecorate pattern you were using, and happily also avoids comparing individual Story instances without ordering support.
但它仍然给我一个错误。这个新的解决方案与新的Django / Python版本不相称?
but, it still gave me an error. This new solution isnt comparable with a new Django/Python version?
推荐答案
是的,它已经改变了一点。现在您必须为排序指定一个 lambda
,因为密钥必须是可调用的东西。
使用 lambda
可以在您正在使用的可迭代对象的每个项目上调用 - 确保键
可以用于您自己的类的任何类型的对象实例。
Yes, it has changed a bit. Now you have to specify a lambda
for your sorting because key has to be something that is callable.
Using lambda
makes it callable on every item of the iterable object which you are using - ensuring that key
can be used across any kind of object instances your own classes.
尝试以下操作:
ranked_stories = sorted(latest_stories, key=lambda story: store.score(), reverse=True)
您可以使用分数
对象使其变得复杂,这就是 lambda
You may make it as complex as you want using the score
object and that's the beauty of lambda
这篇关于Django / Python不顺序类型:complex()< complex()Django教程youtube-croach的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!