gpt4 book ai didi

python - 在 JINJA2 中连接列表

转载 作者:太空狗 更新时间:2023-10-29 16:56:03 25 4
gpt4 key购买 nike

如何在 jinja2 中连接两个列表变量?

例如

GRP1 = [1, 2, 3]
GRP2 = [4, 5, 6]

{# This works fine: #}
{% for M in GRP1 %}
Value is {{M}}
{% endfor %}


{# But this does not: #}
{% for M in GRP1 + GRP2 %}
Value is {{M}}
{% endfor %}

因此,我尝试使用 + 连接两个列表(就像在 Python 中那样),但事实证明它们不是列表,而是 python xrange 对象:

jijna2 error: unsupported operand type(s) for +: 'xrange' and 'xrange'

有没有办法让我在同一个 for 循环中迭代 GRP1 和 GRP2 的串联?

最佳答案

据我所知,您不能使用 native Jinja2 模板来做到这一点。您最好创建一个新的组合迭代器并将其传递给您的模板,例如:

from itertools import chain

x = xrange(3)
y = xrange(3, 7)
z = chain(x, y) # pass this to your template
for i in z:
print i

根据评论,您可以明确地将可迭代对象转换为列表,并将它们连接起来:

{% for M in GRP1|list + GRP2|list %}

关于python - 在 JINJA2 中连接列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15879983/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com