如何对列表中的所有整数进行乘法运算?--Python

1 投票
3 回答
6166 浏览
提问于 2025-04-17 13:20
list1= [1,2,3,4] 

1) 我想把这个列表里的每个元素都乘起来,最后得到24。我该怎么在Python里做到这一点,而不使用for循环?有没有现成的库可以用来实现这个?

2) 如果list1里包含字符串,那该怎么办呢?

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

3) 如果list1里包含字符串,那该怎么办呢?

list1 = ['1234']

3 个回答

0

下面是一个不使用循环来实现乘法的例子(使用递归和尾递归)。

 " 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])
4

你可以在Python中使用 reduce(),或者在Python 3.x中使用 functools.reduce()

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
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

撰写回答