英文:
Nested for loops with numeric values in Django
问题
我有一个如下的二维列表:
my_list = [["2","", "4"],["3", "", ""],["1", "1", ""]]
在Python中,如果我们想知道项目的索引,可以按以下方式迭代上述列表:
for row in range(len(my_list)):
for column in range(len(my_list[row])):
print("Item at position ", row, column)
print(my_list[row][column])
我正在尝试在Django模板中实现上述方法。我可以通过以下方式直接访问元素:
{% for row in my_list %}
上述方法完美运行,但我需要访问索引,这就是为什么我需要嵌套数字循环:
我尝试了以下链接中提供的方法:
Numeric Loops
<br>
我制定了下面提到的解决方案,但它没有打印任何内容:
{% for row in '0123' %}
{% for column in my_list.row %}
<p> {{my_list.row.column}}</p>
{% endfor %}
{% endfor %}
我在上面的代码中做错了什么?是否有更简单的方法?
英文:
I have a 2D List as follows:
my_list = [["2","","4"],["3","",""],["1","1",""]]
In Python, we can iterate over the above-mentioned list if we want to know the index of items in the following way.
for row in range(len(my_list)):
for column in range(len(my_list[row])):
print("Item at position ", row, column)
print(my_list[row][column)
I am trying to implement the above approach in Django Template as well. I can access the element directly in the following manner:
for row in my_list
The above approach works perfectly, but I need to access index and that's why I need Nested Numeric Loops:
I tried the following approach given in this link:
Numeric Loops
<br>
I made a solution mentioned below but it is not printing anything
{% for row in '0123' %}
{% for column in my_list.row %}
<p> {{my_list.row.column}}</p>
{% endfor %}
{% endfor %}
What am I doing wrong in the above code & is there any simpler approach to this?
答案1
得分: 2
Looks like you need forloop.parentloop
& forloop.counter
.
{% for row in my_list %}
{% for column in row %}
<p> {{forloop.parentloop.counter}} {{ forloop.counter }} </p>
<p> {{ column }} </p>
{% endfor %}
{% endfor %}
英文:
Looks like you need forloop.parentloop
& forloop.counter
.
{% for row in my_list %}
{% for column in row %}
<p> {{forloop.parentloop.counter}} {{ forloop.counter }} </p>
<p> {{ column }} </p>
{% endfor %}
{% endfor %}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论