1
list1= [1,2,3,4] 

1)我想将此列表中的每个元素相乘以输出 24。如何在不使用 for 循环的情况下在 python 中执行此操作?是否有内置库可以做到这一点?

2)如果list1包含字符串,例如

list1= ["1,2,3,4"]

3)如果list1包含字符串,例如

list1 = ['1234']
4

3 回答 3

10

您还可以使用:

import operator
reduce(operator.mul, [1,2,3,4])

出去:

24

至于性能,使用operator.mul要快一些:

In [1]: from operator import mul

In [2]: lst = [1,2,3,4]

In [3]: reduce(mul,lst)
Out[3]: 24

In [4]: %timeit reduce(mul,lst)
1000000 loops, best of 3: 733 ns per loop

In [5]: %timeit reduce(lambda x,y:x*y,lst)
1000000 loops, best of 3: 1.28 us per loop

如果您将数字作为字符串:

In [6]: reduce(mul,map(int,["1,2,3,4"][0].split(',')))
Out[6]: 24

对于大型列表,您还可以使用itertools.imap它返回一个迭代器:

In [7]: from itertools import imap

In [8]: %timeit reduce(mul,imap(int,["1,2,3,4"][0].split(',')*10000))
1 loops, best of 3: 264 ms per loop

编辑: 希望您的最后一次编辑:

In [18]: reduce(mul,map(int,['1234'][0]))
Out[18]: 24
于 2013-01-22T06:49:43.020 回答
4

您可以使用reduce(), 或functools.reduce()在 py3x 中:

In [4]: list1= [1,2,3,4]

In [5]: reduce(lambda x,y:x*y,list1)
Out[5]: 24

在 python 3.3 中,您还可以使用itertools.accumulate()

from itertools import islice,accumulate
list1= [1,2,3,4]
le=len(list1)
it=accumulate(list1,operator.mul)
print list(islice(it,le-1,le))[-1]    #prints 24

编辑:如果是字符串,您必须先使用拆分字符串str.split(","),然后将其应用于int()返回的列表:

In [6]: list1= ["1,2,3,4"]

In [7]: reduce(operator.mul,map(int,list1[0].split(",")))
Out[7]: 24
于 2013-01-22T06:47:05.043 回答
0

以下是乘法 w/o 循环的实现(使用递归和尾递归)。

 " A recursive implementation"        
def mul_recursive(nos):
    if len(nos) == 1:
        return nos[0]
    return nos[0] * mul_recursive(nos[1:])


" A tail recursive implementation"
def mul_tailrecursive(nos):
    def multiply(nos,mul_so_far):
        if len(nos) == 1:
            return nos[0]*mul_so_far
        return multiply(nos[1:],mul_so_far * nos[0])
    return multiply(nos,1)

print mul_recursive([1,2,3,4,5])
print mul_tailrecursive([2,3,4])
于 2013-01-22T07:02:05.937 回答