没有库的列表中的整数乘积(Product of integers in list without libraries)
假设我不允许使用库。 如何计算列表中索引的乘积。 我们假设整数都不是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]Let's say I'm not allowed to use libraries. How do I go about calculating the product of indexes in a list. Let's assume none of the integers are 0 or less. The problem gets harder as I'm trying to calculate the indexes vertically.
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]]With numpy the solution for my problem would be:
import numpy as np print([np.prod(l) for l in zip(*bigList)]) [1, 32, 243, 1024, 3125]However without it my solution is much more chaotic:
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] *= cAnd why not simply:
productList = [] for i in range(len(bigList[0]): p = 1 for row in bigList: p *= row[i] productList.append(p)Alternatively, a small improvement over your solution:
productList = [1]* len(bigList[0]) for row in bigList: for i, c in enumerate(row): productList[i] *= c更多推荐
发布评论