I want a result like:
1:
2:
3: 3 p3 33
4: 4 p4 44
....
...
But what I get is
1:
2:
3: 3 p3 33
3: 4 p4 44
3: 7 p7 77
...
This is my python code
str1 = [3,4,7,9]
n_save = ['p3','p4','p7','p9']
d_save = ['33','44','77','99']
zipped = zip(str1,n_save,d_save)
# flask code
{% for i in range(0,10) %}<br>
{% if i 1 in str1|list %}
{% for numm,namee,dd in zipped %}
<option value="{{ i 1 }}"> {{ i 1 }} : {{ namee }} {{ dd }}</option>
{% endfor %}
{% else %}
<option value="{{ i 1 }}"> {{ i 1 }} : </option>
{% endif %}
{% endfor %}
Any help appreciated.
CodePudding user response:
Your issue is at
<option value="{{ i 1 }}"> {{ i 1 }} : {{ namee }} {{ dd }}</option>
% endfor %}
You are looping through the entire zipped array which is currently [(3, 'p3', '33'), (4, 'p4', '44'), (7, 'p7', '77'), (9, 'p9', '99')]
What you want is to only get the members of the tuple at a particular position i.e.
if i 1 = 3 which is at position 0 of str1, then only get values of zipped[0]
if i 1 = 4 which is at position 1 of str1, then only get values of zipped[1]
Try
<!-- first convert to a list -->
{% set k = zipped|list %}
{% for i in range(0,10) %}<br>
{% if i 1 in str1|list %}
<!-- find the position of i 1 -->
{% set j = str1.index(i 1) %}
<!-- get the value at that position -->
{% set l = k[j] %}
<option value="{{ i 1 }}"> {{ i 1 }} : {{ l[0] }} {{ l[1] }} {{l[2]}}</option>
{% else %}
<option value="{{ i 1 }}"> {{ i 1 }} : </option>
{% endif %}
{% endfor %}
Tested this and got
1
2
3 : 3 p3 33
4 : 4 p4 44
5
6
7 : 7 p7 77
CodePudding user response:
In the example below, the iterator is first converted into a list.
A pointer to the current index of the zipped list is then created using a namespace.
Now the respective entry of the list can be unpacked.
{% set data = zipped | list -%}
{% set ctx = namespace(index0=0) -%}
{% for i in range(1,11) -%}
{% if ctx.index0 < (data | length) and i == data[ctx.index0][0] -%}
{% set _, namee, dd = data[ctx.index0] -%}
<option value="{{ i }}">{{ i }} : {{ namee }} {{ dd }}</option>
{% set ctx.index0 = ctx.index0 1 -%}
{% else -%}
<option value="{{ i }}">{{ i }} : </option>
{% endif -%}
{% endfor -%}