使用迭代列表中的索引 [英] Using index from iterated list

查看:125
本文介绍了使用迭代列表中的索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试根据当前在另一个列表中迭代的索引从不同的列表中显示值,但无法弄清楚如何访问各个项目。

I'm trying to display values from a different list based on the index that is currently being iterated over on another list but cannot figure out how to access the individual items..

{% for row in myarray.all %}
    <tr>
    <th>{{ my_other_array_where_I_cant_access_elements.forloop.counter }}</th>
    <td>{{ row }}</td>
    </tr>
{% endfor %}

正如你所看到的,我试图使用 forloop.counter 但是这不显示任何东西,它只是创建一个空的表头元素。

As you can see I have tried to use forloop.counter but this doesn't display anything, it just creates an empty table header element.

我的其他数组被定义在以下视图中,如果我删除 forloop.counter ,那么我可以看到打印到表头的整个数组

My other array is defined within the view as the following, and if I remove the forloop.counter then I am able to see the entire array printed to the table header

 my_other_array_where_I_cant_access_elements = ["X", "Y", "Z", "XX", "YY"]

如果我错过了任何所需的详细信息,请让我知道。

Please let me know if I've missed any required details.

推荐答案

听起来你想要同时迭代两个列表,换句话说, zip() 列表。

It sounds like you want to iterate over two lists at the same time, in other words zip() lists.

如果是这种情况,更好地在视图中执行此操作并在上下文中传递:

If this is the case, it is better to do this in the view and pass inside the context:

headers = ["X", "Y", "Z", "XX", "YY"]
data = zip(headers, myarray.all())
return render(request, 'template.html', {'data': data})

然后,在模板中:

{% for header, row in data %}
    <tr>
        <th>{{ header }}</th>
        <td>{{ row }}</td>
    </tr>
{% endfor %}

这篇关于使用迭代列表中的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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