简体   繁体   English

mako模板和

[英]Mako template sum

I have a problem creating a Mako template, which will take a list of numbers and output their sum. 我在创建Mako模板时遇到问题,该模板将使用数字列表并输出其总和。 Example: 例:

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

output: 输出:

1 + 2 + 3 + 4 + 5

I want the list to be passed as an argument to the template. 我希望列表作为参数传递给模板。 Is the way to go around this using python ' + '.join(list) ? 是使用python ' + '.join(list)解决此问题的方法吗? I know that we can use \\ to escape new line characters and so I could do it in the loop but then special care needs to be taken with regard to the last + , which is quite ugly. 我知道我们可以使用\\来转义换行符,因此可以在循环中使用它,但是对于last + ,则需要特别注意,这非常难看。

Thanks! 谢谢!

Built in function sum() should work just fine, see Python doc for sum 内置函数sum()应该可以正常工作,请参阅Python文档以获取sum

Your template body should contain just 您的模板主体应包含

def template(context, numbers_list): return sum(numbers_list)

Or, if numbers get passed in as string: 或者,如果数字以字符串形式传递:

def template(context, numbers_list): return sum(int(x) for x in numbers_list)

First of all, take note that you should never name your variables after built-in types. 首先,请注意, 永远不要使用内置类型来命名变量。 I am referring to your naming your list ( [1,2,3,4,5] ) as list . 我指的是将您的列表( [1,2,3,4,5] )命名为list This can cause a lot of problems. 这会引起很多问题。

Secondly, you can use this code to get your desired result : 其次,您可以使用以下代码来获得所需的结果:

def return_desired_result_():
    li=[1,2,3,4,5]
    x=''
    for i in range(len(li)) :
    if i < len(li) -1 :
        x += str(li[i]) + " + "
    else :
        x += str(li[i])
    return x

The code is quite hacky and self explanatory , if however you need any more explanation, just comment. 该代码很hacky,易于说明,但是如果您需要更多说明,请注释。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM