如何在Jinja中依据另一个列表对目标列表进行排序?
解决方案
核心思路
把第二个列表里的mac_b映射到基准列表['a', 'b', 'c']中的b,通过提取基准键的方式,用自定义排序规则对齐基准列表的顺序。
完整实现代码
{% set base_order = ['a', 'b', 'c'] %} select {% for field in base_order %} {% if field.startswith('mac_') %} macro_init[{{field}}], {% else %} {{field}}, {% endif %} {% endfor %} union all select {% set target_fields = ['a', 'c', 'mac_b'] %} {% for field in target_fields|sort(key=lambda x: base_order.index(x.replace('mac_', ''))) %} {% if field.startswith('mac_') %} macro_init[{{field}}], {% else %} {{field}}, {% endif %} {% endfor %}
代码说明
- 定义基准排序列表:用
base_order存储目标顺序['a', 'b', 'c'],避免重复编写,方便后续修改维护。 - 第一个SELECT块:直接遍历基准列表,无需额外排序,确保输出顺序与基准完全一致。
- 第二个SELECT块:
- 用
replace('mac_', '')把mac_b转换为b,匹配基准列表里的对应元素。 - 通过
sort(key=lambda x: base_order.index(...)),以基准列表中对应元素的索引作为排序依据,实现和基准顺序对齐。
- 用
- 字段处理逻辑:保留原有的判断逻辑,对
mac_开头的字段生成macro_init[{{field}}],其他字段直接输出名称。
编译后输出
select a, b, c, union all select a, macro_init[mac_b], c,
内容的提问来源于stack exchange,提问作者Tomer Shalhon
相关产品推荐
相关产品推荐

