如何在jinja2中使用enumerate(zip(seq1,seq2))?

3

我正在尝试使用Django来对一些RNA序列进行染色。我使用枚举和zip函数在列表中查找相等的索引。例如:

for i, (a, b) in enumerate(zip(seq1, seq2)):
        if a == b and i not in green:
            <p style="color: green;">{{i}}</p>

        elif a != b and i not in red:
            <p style="color: red;">{{i}}</p>

我在模板中遇到了以下错误:

'for'语句应该使用格式'for x in y':for i, (a, b) in enumerate(zip(seq1, seq2)):

请注意以上代码中的格式问题。


错误仍然存在。 - cacotsuki
3个回答

3

1
这不是Django模板引擎,而是安装在Django中的Jinja模板引擎。 - Willem Van Onsem

2
我认为 Jinja 模板引擎在解析此处 for 循环中的 i,(a,b) 部分时存在问题,因此可能值得为此提交一个支持票。也许这是有意的行为。

无论如何,在此处您可以使用 3 元组进行压缩。作为 zip 的第一个可迭代对象,我们可以取 itertools.count [python-doc]。因此,您将使用 itertools.count() 和引用 'count' 将其传递给上下文,然后进行渲染:

{% for i, a, b in zip(indices(), seq1, seq2) %}
     {# ... #}
{% endfor %}

例如:

>>> from jinja2 import Template
>>> from itertools import count
>>> Template('{% for i, a, b in zip(indices(), seq1, seq2) %} {{ (i, a, b) }}{% endfor %}').render(indices=count, seq1='foobar', seq2='babbaa', zip=zip)
" (0, 'f', 'b') (1, 'o', 'a') (2, 'o', 'b') (3, 'b', 'b') (4, 'a', 'a') (5, 'r', 'a')"

话虽如此,我强烈建议不要在模板中编写业务逻辑。事实上,这也是Django模板引擎一开始不允许这种语法的主要原因。最好在视图中创建zip对象,并通过上下文将其传递给渲染引擎。

2
这段代码可能会有所帮助,尝试使用下面类似的代码,它对我很有效。
(修改自我使用过的一些可用代码)
在Jinja2中使用'for循环'时,使用loop.xxx来访问某些特殊变量。
such as:
  loop.index        # index (1 inexed)
  loop.index0       # index (0 inexed)
  loop.revindex     # reversed ...
  loop.revindex0    # reversed ...
  loop.first        # True if first iteration
  loop.last         # True if last iteration
  loop.length
  loop.depth        # Recursive loop depth
  loop.depth0       # Recursive loop depth (0 inexed)

代码:

{% for (item_a, item_b) in zip(seq1, seq2) %}
{# important note: you may need to export __builtin__.zip to Jinja2 template engine first! I'm using htmlPy for my app GUI, I'm not sure it will or not affect the Jinja2 Enviroment, so you may need this #}
  <tr>
    <td>No.{{ loop.index0 }}</td>{# index (0 inexed) #}
    <td>No.{{ loop.index }}</td>{# index (1 started) #}
    <td>{{item_a}}</td>
    <td>{{item_b}}</td>
  </tr>
{% endfor %}

我的环境:

python 2.7.11 (I have py35 py36 but the code wasn't tested with them)

>py -2
Python 2.7.13 (v2.7.13:a06454b1afa1, Dec 17 2016, 20:53:40) [MSC v.1500 64 bit (AMD64)] on win32
>pip2 show jinja2
Name: Jinja2
Version: 2.8

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接