1

当我在做一个简单的计算器时,我来到了这一点。我做了一个简单的程序来汇总数字列表,如下所示,但是乘法程序有点长。

那么任何人都可以知道如何在python中制作多个数字列表的短程序。这是我的代码。

def calculate(oper,*nm):
    return oper(nm)

add=lambda x:sum(x)

def mult(lst):
    tmp=1
    for i in lst:
        tmp*=i
    return tmp

计算(加,2,34,2)

计算(多,8,5,7)

4

2 回答 2

4

Really, you do not need to define calculate because Python already has a name for it: reduce.

def calculate(oper, *nm):
    return reduce(oper, nm)

In [6]: import operator

In [7]: calculate(operator.add, 2, 34, 2)
Out[7]: 38

In [8]: calculate(operator.mul, 8, 5, 7)
Out[9]: 280

Note: In Python3, reduce has been moved to the functools module. (Thanks to @ErikRoper for pointing this out.)

于 2013-02-04T13:24:10.223 回答
0

You can use the in-built reduce function, which takes a callable, a list and an optional starting element. It calls callable with a tuple (elem, result) where element is the ith element from the list and result is the result so far.

reduce(lambda item,prod: item * prod, range(1, 5), 1)
Out[2]: 24

So the above would call the lambda function first with (1,1), then with (2,1*1) then (3,2*1) and finally (4,3*2)

So you'd define add and mult and replace your calculate with the built-in reduce

add = lambda item,cumul_sum: item + cumul_sum
mult = lambda item,product: item * product 
reduce(add, range(1,5), 0)
Out[5]: 10
reduce(mult, range(1,5), 1)
Out[6]: 24

http://docs.python.org/2.7/library/functions.html?highlight=reduce#reduce

于 2013-02-04T13:23:58.467 回答