如何将这行代码转换为定义的函数以使我的代码更干净?

时间:2014-06-08 21:13:23

标签: python python-2.7

y_total = sum(i for i in y_input)
x_total = sum(i for i in x_input)
z_total = sum(i for i in z_input)
q_total = sum(i for i in q_input)

在我之上,我在Python IDLE中有一小部分代码行,从我的观点来看,这看起来非常重复,我不想为我想要的每一笔总和键入sum(i for i in _____)采取。我仍然是这个Python的初学者,但在此之前我做过一些外部研究。到目前为止,我设法做了类似的事情,但它并不多,因为我不确定如何“概括”代码使其可重用。

def sum():

1 个答案:

答案 0 :(得分:1)

只要y_input& co。是可迭代的,你不需要那个生成器表达式。使用:

y_total = sum(y_input)
x_total = sum(x_input)
z_total = sum(z_input)
q_total = sum(q_input)