Reputation: 651
I don't know how to express my need.I just show the code.
data_lis = [1,2,3,4,5,6,7,8,9]
How can I separate this list into N
parts with 3 element each part?
I do this is in order to render
<div class="card-group d-block d-md-flex u-card--gutters-2-md">
<div class="card border-0 rounded shadow-sm mb-3 transition-3d-hover">element</div>
<div class="card border-0 rounded shadow-sm mb-3 transition-3d-hover">element</div>
<div class="card border-0 rounded shadow-sm mb-3 transition-3d-hover">element</div>
</div>
I need to render the data just like the above style,but how can I dynamically change the render way?
a = [
[3,2,3],
[3,4,2],
[3,2]
]
I just handly separate it into N
parts with 3 elements each part!
Upvotes: 2
Views: 865
Reputation: 1950
you can use syntax Rakesh said
data_list = [data_list[i:min(i+3, len(data_list)] for i in xrange(0, len(data_list_, 3)]
also you can change your syntax in your template like this
{% for i in a %}
{% if forloop.counter0|divisibleby:3 %}
<div class="card-group d-block d-md-flex u-card--gutters-2-md">
{% endif %}
<div class="card border-0 rounded shadow-sm mb-3 transition-3d-hover">
{{ k }}
</div>
{% if forloop.counter0|add:2|divisibleby:3 %}
</div>
{% endif %}
{% endfor %}
{% ifequal a|length|divisibleby:3 False %}
</div>
{% endifnotequal %}
and here you dont want to split content to list of lists.
Upvotes: 1
Reputation: 82785
If I understood correctly you need the template syntax.
Try:
{% for i in a %}
<div class="card-group d-block d-md-flex u-card--gutters-2-md">
{% for k in i %}
<div class="card border-0 rounded shadow-sm mb-3 transition-3d-hover">{{ k }}</div>
{% endfor %}
</div>
{% endfor %}
To divide the list to N chunks use.
data_lis = [1,2,3,4,5,6,7,8,9]
N = 3
a = [data_lis[i:i+N] for i in range(0, len(data_lis), N)]
print(a)
Output:
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Upvotes: 2