Python 使用迭代列表中的索引
我试图根据当前在另一个列表上迭代的索引显示不同列表中的值,但无法确定如何访问单个项Python 使用迭代列表中的索引,python,django,list,django-templates,Python,Django,List,Django Templates,我试图根据当前在另一个列表上迭代的索引显示不同列表中的值,但无法确定如何访问单个项 {% for row in myarray.all %} <tr> <th>{{ my_other_array_where_I_cant_access_elements.forloop.counter }}</th> <td>{{ row }}</td> </tr> {% endfor %} 如果我遗漏了任何
{% for row in myarray.all %}
<tr>
<th>{{ my_other_array_where_I_cant_access_elements.forloop.counter }}</th>
<td>{{ row }}</td>
</tr>
{% endfor %}
如果我遗漏了任何必需的详细信息,请告诉我。听起来您想同时迭代两个列表,换句话说,就是列表 如果是这种情况,最好在视图中执行此操作,并在上下文中传递:
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 %}
{%用于标题,数据%中的行}
{{header}}
{{row}}
{%endfor%}
有一种可能的方法,我刚刚尝试过。但是,仅当您仅将第二个数组用作单个for循环的一部分,而不使用循环索引时,它才起作用:
arr = ["1-0", "1-1"] # your first array
arr2 = ["2-0", "2-1"] # your second array
class wrap(object):
def __init__(self, ref):
self.ref = ref
self.idx = -1
def next(self):
self.idx += 1
return self.ref[self.idx]
return render_to_response('...', { "arr": arr, "wrap": wrap(arr2) })
模板为:
{% for row in arr %}
<h1>Row {{ row }} at {{ forloop.counter }} matches {{ wrap.matching }} </h1>
{% endfor %}
{%for arr%中的行}
{{forloop.counter}}处的{{Row}行与{{wrap.matching}匹配
{%endfor%}
是否应该是forloop.counter0(以0为基础的索引)?@manuBriot-如果是这样的话,我希望它至少会显示一些值(对于记录,我也尝试过,但它仍然没有显示任何值)我刚刚研究了如何实现这一点,但这是不可能的,因为myarray
实际上是另一个对象中更深层次的数组,我希望避免将这些头存储在数据库(对象存储的地方)中。。在模板方面有这样的解决方案吗?还是我必须咬紧牙关,将标题放在数据库中?@Sayse自定义模板过滤器可能是这种情况下的一个选项:。谢谢,我将研究如何实现它,看起来正是我需要的
{% for row in arr %}
<h1>Row {{ row }} at {{ forloop.counter }} matches {{ wrap.matching }} </h1>
{% endfor %}