嵌套的Django中带有数值的for循环。

huangapple go评论76阅读模式
英文:

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 %}
        &lt;p&gt; {{my_list.row.column}}&lt;/p&gt;
    {% endfor %}
{% endfor %}

我在上面的代码中做错了什么?是否有更简单的方法?

英文:

I have a 2D List as follows:

my_list = [[&quot;2&quot;,&quot;&quot;,&quot;4&quot;],[&quot;3&quot;,&quot;&quot;,&quot;&quot;],[&quot;1&quot;,&quot;1&quot;,&quot;&quot;]]

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(&quot;Item at position &quot;, 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 &#39;0123&#39; %}
    {% for column in my_list.row %}
        &lt;p&gt; {{my_list.row.column}}&lt;/p&gt;
    {% 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 %}
        &lt;p&gt; {{forloop.parentloop.counter}} {{ forloop.counter }} &lt;/p&gt;
        &lt;p&gt; {{ column }} &lt;/p&gt;
    {% endfor %}
{% endfor %}

MoreInfo

英文:

Looks like you need forloop.parentloop & forloop.counter.

{% for row in my_list %}
    {% for column in row %}
        &lt;p&gt; {{forloop.parentloop.counter}} {{ forloop.counter }} &lt;/p&gt;
        &lt;p&gt; {{ column }} &lt;/p&gt;
    {% endfor %}
{% endfor %}

MoreInfo

huangapple
  • 本文由 发表于 2020年1月6日 16:05:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/59608606.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定