没有库的列表中的整数乘积(Product of integers in list without libraries)

编程入门 行业动态 更新时间:2024-10-10 16:19:44
没有库的列表中的整数乘积(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] *= c

And 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

更多推荐

本文发布于:2023-07-31 08:07:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1342045.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:乘积   整数   列表中   Product   list

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!