You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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 %}  

代码说明

  1. 定义基准排序列表:用base_order存储目标顺序['a', 'b', 'c'],避免重复编写,方便后续修改维护。
  2. 第一个SELECT块:直接遍历基准列表,无需额外排序,确保输出顺序与基准完全一致。
  3. 第二个SELECT块:
    • 用replace('mac_', '')把mac_b转换为b,匹配基准列表里的对应元素。
    • 通过sort(key=lambda x: base_order.index(...)),以基准列表中对应元素的索引作为排序依据,实现和基准顺序对齐。
  4. 字段处理逻辑:保留原有的判断逻辑,对mac_开头的字段生成macro_init[{{field}}],其他字段直接输出名称。

编译后输出

select
        a,
        b,
        c,
    
union all

select
        a,
        macro_init[mac_b],
        c,

内容的提问来源于stack exchange,提问作者Tomer Shalhon

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.26 03:12:52