python-列表中没有库的整数乘积
作者:互联网
假设我不允许使用库.
如何计算列表中索引的乘积.
假设所有整数都不小于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]
解决方法:
为什么不简单地:
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
标签:zip,python,numpy,list-comprehension 来源: https://codeday.me/bug/20191025/1931857.html