我正在尝试执行以下操作(不起作用,只是为了传达预期的行为):
<table>
<tr>
<th>Column 1</th>
<th>Column 2</th>
<th>Column 3</th>
</tr>
{% for col1_val in col1_values %}
<tr>
<td>{{ col1_val }}</td>
<td>{{ col2_values[col1_values.index(col1_val)] }}</td>
<td>{{ col3_values[col1_values.index(col1_val)] }}</td>
</tr>
{% endfor %}
</table>
所需的表是:
Column 1 Column 2 Column 3
col1_values[0] col2_values[0] col3_values[0]
col1_values[1] col2_values[1] col3_values[1]
.
.
.
其中 col1_values 彼此唯一。
Jinja2模板应该如何改写才能达到想要的表格输出?是否可以不必转置 col1_values、col2_values 和 col3_values 的维度?如果不是,那么进行转置的最 Pythonic 方式是什么?
最佳答案
为什么不使用嵌套列表呢?遍历如下结构:
table_values = [[col1_value_0, col2_value_0, col3_value_0], [col1_value_1, col2_value_1, col3_value_1], ...]
zip() function如果需要,可以组合 3 个 colX_values 列表:
table_rows = zip(col1_values, col2_values, col3_values)
现在您有每行列表可以循环:
{% for col1_val, col2_val, col3_val in table_rows %}
<tr>
<td>{{ col1_val }}</td>
<td>{{ col2_val }}</td>
<td>{{ col3_val }}</td>
</tr>
{% endfor %}
关于python - 如何使用模板(例如 Jinja2)将列值列表呈现到表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16633566/