Jinja2中的稳定排序 [英] Stable sorting in Jinja2

查看:51
本文介绍了Jinja2中的稳定排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可以在Jinja2中依次应用排序过滤器来对列表进行排序首先是一个属性,然后是另一个属性?这似乎是很自然的事情,但是在我的测试中,先前的排序是完全不稳定的,所有排序都丢失了.

It is possible to apply the sort filter in Jinja2 successively to sort a list first by one attribute, then by another? This seems like a natural thing to do, but in my testing, the preceeding sort is completely unstable and all sorting is lost.

我已经通过在将列表传递给模板之前先在python中排序来解决此问题,但我想知道是否有可能在Jinja2中对稳定"进行排序.

I already worked around it by sorting first in python before passing the list to the template, but I would like to know if it's possible to sort "stable" in Jinja2.

我应用过滤器的方式如下:

The way I applied the filter was like so:

{{ item_list|sort(attribute='value')|sort(attribute='color') }}

我希望看到的是按color排序的列表,而元素共享按value排序的颜色.相反,它看起来就像从未发生过value排序一样.

What I had hoped to see was the list sorted by color, with the elements sharing a color sorted by value. Instead, it looked the same as if the value sort never happened.

例如,从此列表中:

2 red
3 blue
3 red
2 blue
1 blue
4 red

我想要这样的东西:

1 blue
2 blue
3 blue
2 red
3 red
4 red

我查看了 groupby 过滤器,但是该实现似乎太复杂了(需要嵌套用于循环).

I looked at the groupby filter but that implementation seems too complicated (would require nested for loops).

推荐答案

我不知道可以执行此操作的本机jinja2过滤器.要基于多个属性对列表进行排序,您可以定义自定义过滤器在jinja2中.

I am not aware of a native jinja2 filter that can do this. To sort a list based on multiple attributes,you can define a custom filter in jinja2.

从接受的答案到此问题,您可以编写自己的问题过滤器

From the accepted answer to this question, you can write your own filter

import operator

def sort_multi(L,*operators): 
    L.sort(key=operator.itemgetter(*operators))
    return L

在您的应用程序环境中注册.因此,对于pyramid,您将执行类似的操作

Register it in your application environment. So for pyramid, you would do something like

env = config.get_jinja2_environment()
env.filters['sort_multi'] = sort_multi

最后在您的模板中

{{item_list|sort_multi('value','color')}}

这篇关于Jinja2中的稳定排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆