Using index from iterated list

后端 未结 2 1219
萌比男神i
萌比男神i 2020-12-07 00:28

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 individu

相关标签:
2条回答
  • 2020-12-07 00:53

    There is a possible approach, which I just tried. It only works if you only use the second array as part of a single for loop, though, and does not use the loop index:

    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) })
    

    And the template is:

    {% for row in arr %}
    <h1>Row {{ row }} at {{ forloop.counter }} matches {{ wrap.matching }} </h1>
    {% endfor %}
    
    0 讨论(0)
  • 2020-12-07 01:04

    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})
    

    Then, in the template:

    {% for header, row in data %}
        <tr>
            <th>{{ header }}</th>
            <td>{{ row }}</td>
        </tr>
    {% endfor %}
    
    0 讨论(0)
提交回复
热议问题