没有库的列表中的整数乘积

时间:2017-07-13 13:09:51

标签: python numpy zip list-comprehension

假设我不允许使用库。 如何计算列表中索引的乘积。 我们假设整数都不是0或更小。 当我试图垂直计算索引时,问题变得更加困难。

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

使用numpy解决我的问题的方法是:

import numpy as np   
print([np.prod(l) for l in zip(*bigList)])

[1, 32, 243, 1024, 3125]

然而没有它,我的解决方案就更加混乱:

rotateY = [l for l in zip(*bigList)]
productList = [1]* len(bigList)
count = 0
for l in rotateY:
    for i in l:
        productList[count] *= i
    count += 1
print(productList)

[1, 32, 243, 1024, 3125]

4 个答案:

答案 0 :(得分:2)

您可以迭代每一行,获取每一行 n -th元素,并将每个元素相乘:

>>> from functools import reduce
>>> 
>>> def mul_lst(lst):
    return reduce(lambda x, y: x * y, lst)

>>> 
>>> bigList = [[1, 2, 3, 4, 5],
       [1, 2, 3, 4, 5],
       [1, 2, 3, 4, 5],
       [1, 2, 3, 4, 5],
       [1, 2, 3, 4, 5]]
>>> 
>>> [mul_lst([row[i] for row in bigList]) for i in range(len(bigList))]
[1, 32, 243, 1024, 3125]

如果您不能使用任何库,包括functools,您可以手动编写mul_lst函数的逻辑:

>>> def mul_lst(lst):
    product = lst[0]
    for el in lst[1:]:
        product *= el
    return product

>>> mul_lst([3, 3])
9
>>> mul_lst([2, 2, 2, 2, 2])
32

答案 1 :(得分:1)

为什么不简单:

productList = []
for i in range(len(bigList[0]):
    p = 1
    for row in bigList:
        p *= row[i]
    productList.append(p)

或者,对解决方案的改进很小:

productList = [1]* len(bigList[0])
for row in bigList:
    for i, c in enumerate(row):
        productList[i] *= c

答案 2 :(得分:1)

我们可以转置嵌套列表,然后在每个元素(列表)上使用Python 2.x中的reduce(Python内置)作为单行 -

>>> [reduce(lambda a,b: a*b, i) for i in map(list, zip(*bigList))]
[1, 32, 243, 1024, 3125]

答案 3 :(得分:0)

这是一个快速递归的解决方案

<div class="myHeight">
this uses 80% of total height with 'calc'
</div>
<div class="myVhHeight">
this uses 40% of view port  height with 'vh'
</div>