限制排序方法的输出
如果我的视图代码是:
arttags = sorted(arttags, key=operator.attrgetter('date_added'), reverse=True)
将结果限制为 50 个标签的参数是什么?
我假设这
.... limit=50)
是不正确的。
更完整的代码如下:
videoarttags = Media.objects.order_by('date_added'),filter(topic__exact='art')
audioarttags = Audio.objects.order_by('date_added'),filter(topic__exact='art')
conarttags = Concert.objects.order_by('date_added'),filter(topic__exact='art')
arttags = list(chain(videoarttags, audioarttags, conarttags))
arttags = sorted(arttags, key=operator.attrgetter('date_added'), reverse=True)
如何合并 –
itertools.islice(sorted(...),50)
if my views code is:
arttags = sorted(arttags, key=operator.attrgetter('date_added'), reverse=True)
what is the argument that will limit the result to 50 tags?
I'm assuming this:
.... limit=50)
is incorrect.
more complete code follows:
videoarttags = Media.objects.order_by('date_added'),filter(topic__exact='art')
audioarttags = Audio.objects.order_by('date_added'),filter(topic__exact='art')
conarttags = Concert.objects.order_by('date_added'),filter(topic__exact='art')
arttags = list(chain(videoarttags, audioarttags, conarttags))
arttags = sorted(arttags, key=operator.attrgetter('date_added'), reverse=True)
how do incorporate –
itertools.islice(sorted(...),50)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您可能还想将 [:50] 添加到每个
objects.order_by.filter
调用中。 这样做意味着您只需在 Python 中对内存中的 150 个项目进行排序,而不是更多。You might also want to add [:50] to each of the
objects.order_by.filter
calls. Doing that will mean you only ever have to sort 150 items in-memory in Python instead of possibly many more.我想我几乎是找错了树。 我试图完成的事情实际上非常简单,使用模板过滤器(切片),但我不知道我能做到。
代码如下:
是的,我觉得很愚蠢,但我很高兴我完成了:-)
I think I was pretty much barking up the wrong tree. What I was trying to accomplish was actually very simple using a template filter (slice) which I didn't know I could do.
The code was as follows:
Yes, I feel pretty stupid, but I'm glad I got it done :-)
我相信,您想要的总体思路是
take
。 来自 itertools 文档:The general idea of what you want is a
take
, I believe. From the itertools documentation:您可能会发现切片适合您:
You'll probably find that a slice works for you:
heapq.nlargest 怎么样:
返回由 iterable.key 定义的数据集中包含 n 个最大元素的列表,如果提供,则指定一个参数函数,用于从可迭代中的每个元素中提取比较键: key=str.lower 等价到:已排序(可迭代,key=key,reverse=True)[:n]
what about heapq.nlargest:
Return a list with the n largest elements from the dataset defined by iterable.key, if provided, specifies a function of one argument that is used to extract a comparison key from each element in the iterable:
key=str.lower Equivalent to: sorted(iterable, key=key, reverse=True)[:n]