有没有办法在 Django 中同时循环两个列表? [英] is there a way to loop over two lists simultaneously in django?

查看:33
本文介绍了有没有办法在 Django 中同时循环两个列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个长度相同的列表对象,我想渲染互补数据,有没有办法同时渲染两个对象,即.

{% for i,j in table, total %}{{ 一世 }}{{ j }}{% 结束为 %}

或类似的东西?

解决方案

如果两个列表的长度相同,您可以在视图中返回 zipped_data = zip(table, total) 作为模板上下文,它产生一个二值元组的列表.

示例:

<预><代码>>>>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 }}{% 结束为 %}

另外,看看 Django 的关于 for 模板标签的文档 这里.它提到了使用它的所有可能性,包括很好的例子.

I have two list objects of the same length with complementary data i want to render is there a way to render both at the same time ie.

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

or something similar?

解决方案

If both lists are of the same length, you can return zipped_data = zip(table, total) as template context in your view, which produces a list of 2-valued tuples.

Example:

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

In your template, you can then write:

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

Also, take a look at Django's documentation about the for template tag here. It mentions all possibilities that you have for using it including nice examples.

这篇关于有没有办法在 Django 中同时循环两个列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆