python - 有没有办法在 Django 中同时循环两个列表?

标签 python django django-templates django-views

我有两个相同长度的列表对象和我想要呈现的互补数据,有没有办法同时呈现两者,即。

{% for i,j in table, total %} 
 {{ i }} 
 {{ j }}
{% endfor %} 

或类似的东西?

最佳答案

如果两个列表的长度相同,您可以返回 zipped_data = zip(table, total) 作为 View 中的模板上下文,这会生成一个双值元组列表。

例子:

>>> lst1 = ['a', 'b', 'c']
>>> lst2 = [1, 2, 3]
>>> zip(lst1, lst2)
[('a', 1), ('b', 2), ('c', 3)]

在你的模板中,你可以这样写:

{% for i, j in zipped_data %}
    {{ i }}, {{ j }}
{% endfor %}

此外,请查看 Django 关于 for 模板标签的文档 here .它提到了您使用它的所有可能性,包括很好的示例。

关于python - 有没有办法在 Django 中同时循环两个列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14841165/

相关文章:

django - 如何将一些信息传递到 View 而不将其包含在 URL 中(django 新手)

python - ctype - python - long int 太长无法转换 -

Python - 计算日期范围内的唯一标签

python - 在服务器中更改 Django 的数据库结构

python - Django 相当于 mako 的可调用 block

javascript - 如何在 javascript 中编写 if else 语句

python - 逐个构建 DataFrame 的最快方法是什么?

python - 如何使用 python argparse 解析可选参数?

python - Django:在 GenericStackedInline 上禁止 can_delete

python - 以 10 为基数的 int() 的文字无效 : 'marlm'