英文:
How to add float values from array in for-loop in Jinja template?
问题
我对Python还很陌生,所以我觉得我的想法可能有缺陷。但我认为在Jinja2模板中使用for循环将一些值相加应该很简单。但出于我不知道的原因,用我对这种语言的初步了解来说,这似乎做不到。我希望你们能帮我解决这个问题。
我有一个包含一些Python浮点数的数组:
floatArray = [1.5,3.6,5.8,9.8,10,5.0]
我将这个数组传递给我的模板:
render_template("array.html", floatArray=floatArray,)
在我的模板中,我想将这些值相加:
{% for x in floatArray %}
{% set total = x + total %}
{{ x }} - {{ total }}<br>
{% endfor %}
<br>{{ total }}
这是我得到的结果:
3.6 - 3.6
5.8 - 5.8
9.8 - 9.8
10 - 10.0
5.0 - 5.0
0.0
我期望的是值的第二列会与前面的值相加:1.5,5.1,10.9,等等。最后一个数字应该是这些值的总和:35.7
由于某种原因,{{total}}的值在每次迭代后重置。有办法阻止这种情况发生吗?
当然,我可以使用:
{{ float_array|sum() }}
但这不够。我的代码中有几个for循环,我想对这些循环的部分进行求和。
请指导我走向正确的方向
英文:
I'm quite new to Python, so it's highely likely that my thinking is flawed on this matter. But I thought it would be quite simple to add some values together in a for-loop in a Jinja2 template. Due to reasons unknown to me, it can't be done with my rudimentair knowledge of this language. I hope you lot can help me with this.
I have an array with some floats in Python:
floatArray = [1.5,3.6,5.8,9.8,10,5.0]
I pass that array through in my template:
render_template("array.html", floatArray=floatArray,)
In my template I want to add these values together:
{% set total = 0.0 %}
{% for x in floatArray %}
{% set total = x + total %}
{{ x }} - {{ total }}<br>
{% endfor %}
<br>{{ total }}
This is the result I get:
1.5 - 1.5
3.6 - 3.6
5.8 - 5.8
9.8 - 9.8
10 - 10.0
5.0 - 5.0
0.0
What I expect is that the second column of the values will add up with the previous ones: 1.5, 5.1, 10.9, etc. The last number should be the total sum of the values: 35.7
For some reason the value of {{total}} resets itself after every iteration. Is there a way to prevent that from happening?
Of course I can use:
{{ float_array|sum() }}
But that won't be sufficient. I have several for loops in my code and I want to sum parts of those loops.
Please kick me in the right direction
答案1
得分: 0
for
语句在 Jinja2 中创建新的作用域。你可以创建一个 namespace
变量,以允许从内部作用域访问该变量:
{% set ns = namespace(total=0.0) %}
{% for x in floatArray %}
{% set ns.total = x + ns.total %}
{{ x }} - {{ ns.total }}<br>
{% endfor %}
<br>{{ ns.total }}
英文:
The for
statement creates a new scope in Jinja2. You can create a namespace
variable instead to allow access to the variable from an inner scope:
{% set ns = namespace(total=0.0) %}
{% for x in floatArray %}
{% set ns.total = x + ns.total %}
{{ x }} - {{ ns.total }}<br>
{% endfor %}
<br>{{ ns.total }}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论