How to print elements of list of an unknown number of zipped lists in Django templates

Question:

a = [1,2,3,4,5]

b = [[3,4],[4,5],[6,7]]

out = [[x if x in l else 'X' for x in a] for l in map(set, b)]

#out:   [['X', 'X', 3, 4, 'X'], ['X', 'X', 'X', 4, 5], ['X', 'X', 'X', 'X', 'X']]

z = zip(a,*out)

In above code the list a will have fix number of elements but list b will be varying, hence elements in z will vary as well.

Now in Django template I would Like to print the elements of z.

What I tried for above scenario is

{% for d,s1,s2,s3 in z %}
<tr>
<td> {{d}} </td>
<td> {{s1}} </td>
<td> {{s2}} </td>
<td> {{s3}} </td>
</tr>
{% endfor %}
1   X   X   X
2   X   X   X
3   3   X   X
4   4   4   X
5   X   5   X 

Which works fine if I know the number of elements present in the z; but unfortunately it’s varying. Sometimes it could have 10 lists , sometimes nothing.

Sometimes the scenario will be like below:

{% for d,s1 in z %}
<tr>
<td> {{d}} </td>
<td> {{s1}} </td>
</tr>
{% endfor %}

1   X
2   X
3   3
4   4
5   X 

So How can I correct above template code to print variable number of list elements in the table?

Thanks.

Asked By: Jazz365

||

Answers:

A quick solution could be to perform two for loops. The first one will iterate through the each of the tuples, and the second could print each of the values of that tuple. Like this:

{% for tuple in z %}
  <tr>
  {% for value in tuple %}
    <td> {{value}} </td>
  {% endfor %}
  </tr>
{% endfor %}

For the exact same result as you wish you will need to transpose the list first.

Answered By: Jope Algorta
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.